Android studio alertdialog custom layout

Полный список

— используем свои View для построения диалога

Кроме сообщения или списка мы можем помещать в диалог свои View-компоненты. Для этого доступно как основное тело диалога, так и заголовок. Для этого нам необходимо создать View и с помощью методов setCustomTitle или setView вставить этот View соответственно в заголовок или тело диалога. Я буду использовать только setView и работать с телом диалога. Использование метода setCustomTitle и работа с заголовком диалога полностью аналогична.

Нарисуем приложение, которое будет использовать свой View-компонент в теле диалога и рассмотрим, как можно модифицировать содержимое этого компонента. Будем добавлять и удалять TextView в теле диалога.

Project name: P0651_AlertDialogCustom
Build Target: Android 2.3.3
Application name: AlertDialogCustom
Package name: ru.startandroid.develop.p0651alertdialogcustom
Create Activity: MainActivity

В strings.xml пропишем тексты:

main.xml – экран с двумя кнопками для удаления и добавления элементов в диалог

dialog.xml – наше будущее кастом-тело диалога.

В tvTime— будем отображать текущее время, а в tvCount – кол-во добавленных TextView.

Рассмотрим код. В методе onCreate выполняем стандартные процедуры и создаем коллекцию textViews для хранения добавляемых TextView.

Метод onclick – обработчик нажатий на кнопки, сохраняет в btn идентификатор нажатой кнопки и показывает диалог.

В методе создания диалога onCreateDialog мы задаем текст заголовка диалога, создаем view из layout-файла dialog.xml и с помощью метода setView говорим диалогу, что надо использовать наше view в качестве тела диалога. И теперь, работая с view, мы будем формировать тело диалога. В только что созданном view сразу находим tvCount – для отображения кол-ва добавленных TextView.

Метод onPrepareDialog – здесь мы с помощью метода getWindow получаем доступ к View-компонентам диалога, находим среди них tvTime и показываем в нем время. Далее определяем, какая кнопка была нажата. Если кнопка добавления, то создаем TextView и помещаем его в view (который определили в методе onCreateDialog) и добавляем в коллекцию textViews. Таким образом TextView добавится в тело диалога. Если же хотим удалить TextView, то находим в коллекции последний добавленный и удаляем его из компонента view и из коллекции textViews. В конце обновляем счетчик кол-ва добавленных TextView в диалоге.

Обратите внимание, что я использую два разных способа для получения доступа к tvCount и tvTime. tvCount я нашел сразу после создания view в методе onCreateDialog. А в случае с tvTime я показываю, как найти View-компонент в диалоге без использования объекта view. Какой вам удобнее по ситуации, тот и используйте.

Все сохраним и запустим приложение. Нажмем кнопку Добавить

Появился диалог. Отображает время, кол-во добавленных TextView и собственно сами добавленные TextView.

Закрываем диалог кнопкой Назад, жмем еще раз добавить

Добавилось еще одно TextView.

Закрываем диалог, жмем кнопку Удалить.

Последнее TextView удалилось.

На следующем уроке:

— рассматриваем обработчики событий диалога
— программно закрываем и показываем диалог

Читайте также:  Топ проводников для андроида

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Диалоговые окна в Android. Часть 1

Dialog

Dialog — это класс, принадлежащий Android SDK и помогающий нам, простым смертным программистам, работать с диалоговыми окнами в Android. Класс Dialog имеет 4 подкласса:

  • AlertDialog: это диалоговое окно для различных сообщений приложения, например «Вы хотите купить мое приложение?» или что то в этом роде. AlertDialog поддерживает три кнопки — утвердительную (OK), отрицательную (Cancel) и нейтральную (Later).
  • ProgressDialog: это диалоговое окно для отображения выполнения различных процессов, загрузки, например.
  • DatePickerDialog: диалоговое окно предлагает пользователю выбрать дату.
  • TimePickerDialog: диалоговое окно предлагает пользователю выбрать время

На первом из этого списка, AlertDialog мы и остановимся подробнее.

AlertDialog

Чтобы создать диалоговое окно AlertDialog нам в помощь потребуется экземпляр класса Builder:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Теперь, когда у нас есть builder, мы можем «строить» свое собственное диалоговое окно. В параметры диалогового окна Вы можете написать множество различных параметров, но основными являются эти:

  • setTitle(int resID) — задает заголовок диалогового окна, принимает в качестве аргументов ссылку на ресурс или строку.
  • setMessage(int resID) — задает сообщение в диалоговом окне, также принимает ссылку на ресурс или строку.
  • setPositiveButton(int textID, DialogInterface.OnClickListener listener) — устанавливает на Вашем диалоговом окне утвердительную кнопку с текстом ресурса textID и слушателем listener. Методы setNegativeButton и setNeutralButton идентичны, с разницей в назначении кнопок.

Пример создания AlertDialog:

В этом примере я использовал setCancelable(true) — это разрешает пользователю закрывать диалоговое окно с помощью хардварной кнопки Back. Еще я создал слушателя для утвердительной кнопки и использовал метод create(). Метод create() возвращает готовое диалоговое окно с вашими параметрами как экземпляр класса AlertDialog.
Вот мы и создали диалоговое окно! Следующая задача — показать его пользователю. Вот тут есть несколько вариантов:

  • showDialog(AlertDialog dialog) — самый простой способ показать диалоговое окно, но начиная с версии 3.0 разработчики Android не рекомендуют пользоваться этим методом, и в результате вы получите предупреждение, которое можно обойти только @SurpressWarning, что есть не совсем хорошо.
  • AlertDialog dialog.show() — альтернативный способ показать окно, для этого в экземпляре dialog должен лежать результат метода Builder.create().

Второй метод нам подходит больше, но писать в основной активности кучу различных Buider и AlertDialog портит читабельность кода. Поэтому целесообразней вынести создание и обработку диалоговых окон в новый класс, например:

Единственная заметка по поводу этого кода будет про использования метода setView(View view) в диалоге IDD_SETTINGS. У AlertDialog как и у всех остальных диалоговых окон есть одна приятная особенность — им можно задавать собственные Layout, что позволяет полностью видоизменять диалоговые окна и их содержимое. Здесь есть один подводный камень: обработку элементов этого Layout вы должны будете производить именно в той Activity, где вызываете это диалоговое окно. Например я показываю диалоговое окно IDD_SETTINGS в MainActivity с Layout по имени settings:

Соответственно я загружаю это окно в MainActivity:

Метод initSettings класса MainActivity в данном случае будет выглядеть так:

Ну а дальше обрабатываете свои объекты как вам угодно.

Небольшой итог

1) Для большинства целей диалоговых окон подходит AlertDialog
2) AlertDialog может принимать вид layout с любыми объектами
3) Гораздо лучше использовать для диалоговых окон отдельный класс и пользоваться AlertDialog.show()
4) Обработка объектов кастомного layout производится в активности, вызвавшей диалог

Читайте также:  Сталкер apk для андроид

В следующей части этой статьи пойдет речь о DialogFragment, который был включен в Android SDK начиная с 3.0 Honeycomb. Надеюсь эта статья поможет новичкам и не очень в своих квестах по завоеванию Google Play.

Источник

Android Custom AlertDialog Tutorial Using Kotlin

by Dody Prasetya · January 18, 2020

Whenever you need to show a custom message or alert on your app, then you need an Android custom AlertDialog. It is very easy to learn and implement! You want to show an alert containing a message? Or, you want to show a custom style alert? Then this tutorial is right for you.

Basically the alert message on Android is using an existing class from the Android framework and that is the AlertDialog. It has many styles like displaying a simple alert message, a multiple choices alert, a list of items alert, a custom layout alert dialog, etc.

What the app will look like?

The app will look like this after you finish this tutorial:

What will you learn?

  • Understand how to implement and show an AlertDialog on the Android app.
  • Learn about different types of AlertDialog (simple, multiple choices, list of items, custom layout, etc) and use some of them.
  • Implement the listener from AlertDialog buttons.

Note: In this post, I used Android Studio 3.5.3, make sure you use the latest Android Studio, or if you already install it, be sure to check the latest update. The Kotlin version that I used is Kotlin 1.3.61.

Getting Started – Android Custom AlertDialog

Open your Android Studio and choose to Start a new Android Studio Project. Then set the Application Name CustomAlertDialog and select Kotlin as the language. Give the Activity Name MainActivity and wait until the Android Studio finishes preparing your project.

Open activity_main.xml inside res/layout directory and replace the code given below:

That’s it for the first step of creating a screen that contains some buttons to show each alert dialog later.

Next, open MainActivity.kt file and add each of these functions:

Simple AlertDialog

Add a new function showSimpleAlert() here:

There are some methods or function from AlertDialog that we use here:

  • setTitle() is for giving the dialog a title.
  • setMessage() is setting a message for the dialog.
  • setPositiveButton() . This method is for giving the dialog a positive button and its listener/action when the button is pressed.
  • setNegativeButton()
  • setNeutralButton()
  • show() , this function is to show the AlertDialog.

List of Items AlertDialog

Add a new function showListAlert() here:

The setItems() function takes a parameter that is an Array of Strings as a list of items for it.

Multiple Choices AlertDialog

Add a new function showMultipleChoicesAlert() here:

The setMultiChoiceItems() is also takes a parameter of Array of Strings. There is also a conditional ( isChecked ) to point out which items that have already been selected.

Custom AlertDialog

Add a new function showCustomAlert() here:

Create a new layout resource file named dialog_custom_layout.xml and put this code inside it:

The setView() is a method to set the custom view or layout of the dialog. In this case, we inflate the dialog_custom_layout.xml to the view and put is as a parameter to setView() .

EditText AlertDialog

Add a new function showSimpleAlert() here:

It is similar to the custom dialog style before, but the difference is the view is created programmatically. This example is an EditText.

Читайте также:  Фильтры экрана для андроид

So, that is all for AlertDialog types for this tutorial. The next step is setting the listeners for each button that you created earlier. Open MainActivity.kt again, and modify the onCreate() method.

And now it is time to run the app and see the dialogs yourself!

Where to go next?

You can download this full code from the link below:

Be sure to check my other cool posts here about:

Hope you like my post, comment and share it with love!

Источник

Create AlertDialog with Custom Layout using XML Layout

As application grows or while building an application for larger group, sometimes it is necessary to use a custom layout in the AlertDialog. The situation can be visualised by having a login dialog, where user would be asked for their login credentials.

While creating custom layout for AlertDialog, we have two options, if the custom UI is simple enough to display one or two components then this could be done programmatically, else we need to create an XML layout and include that into the AlertDialog.

This post is third in series of tutorials for creating and displaying AlertDialog.

Series Index of AlertDialog

  1. Create AlertDialog and Basic Usage
  2. Provide Selection from a list of options
  3. Create AlertDialog with Custom Layout using XML Layout
  4. Create AlertDialog with custom layout programmatically
  5. Create AlertDialog with complex custom layout programmatically
  6. Override Button of AlertDialog

Create Android Application Project

If you are new to Android Studio, then you could learn about creating new projects from our tutorial Create Android Application Project in Android Studio Continued.

Create Android application project with following attributes.

Project Name Custom Alert Dialog
Package Name com.pcsalt.example.customalertdialog
Minimum SDK Version 16
Activity Type Empty Activity
Activity Name MainActivity
Layout Name activity_main

Prepare layout to be displayed in the AlertDialog

We will create a dialog with two input boxes (TextInputEditText) which will demonstrate a login form.

layout_custom_dialog.xml: This layout will be inflated inside AlertDialog to ask user for Username and Password. And, on click of Login a Toast message will be displayed with username and password.

Create layout for MainActivity

activity_main.xml: In the MainActivity, we will display a button which will display an AlertDialog .

Update MainActivity to display AlertDialog with custom layout using XML

MainActivity.java: In MainActivity, we will implement following behaviors:
– Click on Button will display an Alertdialog
– AlertDialog will use the XML layout to display UI components
– CheckBox will toggle the password view
– Click on Login will display a Toast message with username and password.

Screenshots:

Download Source Code

The complete source code is pushed to GitHub repo. Browse it by clicking on the octocat icon.

Display item selected from AutoCompleteTextView in Chip – Android

In this blog we are going to display a list of planets in an AutoCompleteTextView. The list of planets will…

Display progress using ProgressBar – Android

The scenario is to display progress in a ProgressBar and the percentage in a TextView. Once the download is complete,…

Add border to just one side of View – Android

At some point there is a need to display a layout with border(s). And sometimes the border is required in…

BottomSheetDialogFragment – Disable Cancel on Touch Outside and Drag – Android

Disable Cancel on Touch Outside & on Back press In order to create a BottomSheetDialogFragment which should not dismiss on…

Источник

Оцените статью