Android custom dialog fragment

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

— работаем с DialogFragment

Продолжаем рассматривать наследников Fragment. DialogFragment – отличается от обычного фрагмента тем, что отображается как диалог и имеет соответствующие методы.

Построить диалог можно двумя способами: используя свой layout-файл и через AlertDialog.Builder. Нарисуем приложение, которое будет вызывать два диалога, построенных разными способами.

Project name: P1101_DialogFragment
Build Target: Android 4.1
Application name: DialogFragment
Package name: ru.startandroid.develop.p1101dialogfragment
Create Activity: MainActivity

Добавим строки в strings.xml:

Мы будем создавать два диалога, соответственно нам понадобятся два фрагмента.

Создадим layout-файл для первого фрагмента.

Так будет выглядеть наш диалог – текст сообщения и три кнопки.

Создаем класс Dialog1.java:

В onCreateView мы получаем объект Dialog с помощью метода getDialog и устанавливаем заголовок диалога. Далее мы создаем view из layout, находим в нем кнопки и ставим им текущий фрагмент в качестве обработчика.

В onClick выводим в лог текст нажатой кнопки и сами явно закрываем диалог методом dismiss.

Метод onDismiss срабатывает, когда диалог закрывается. Пишем об этом в лог.

Метод onCancel срабатывает, когда диалог отменяют кнопкой Назад. Пишем об этом в лог.

Создаем второй фрагмент. Здесь мы будем строить диалог с помощью билдера, поэтому layout-файл не понадобится. Создаем только класс Dialog2.java:

Обычно для заполнения фрагмента содержимым мы использовали метод onCreateView. Для создания диалога с помощью билдера используется onCreateDialog. Создаем диалог с заголовком, сообщением и тремя кнопками. Обработчиком для кнопок назначаем текущий фрагмент.

В onClick определяем, какая кнопка была нажата и выводим соответствующий текст в лог. В случае создания диалога через билдер, диалог сам закроется по нажатию на кнопку, метод dismiss здесь не нужен.

Методы onDismiss и onCancel – это закрытие и отмена диалога, аналогично первому фрагменту.

Меняем layout-файл для MainActivity — main.xml:

Здесь только две кнопки.

Создаем диалоги и запускаем их методом show, который на вход требует FragmentManager и строку-тэг. Транзакция и коммит происходят внутри этого метода, нам об этом думать не надо.

Все сохраняем и запускаем приложение.

Отобразился наш простенький диалог.

Жмем какую-нибудь кнопку, например, Yes — диалог закрылся. Смотрим логи:

Dialog 1: Yes
Dialog 1: onDismiss

Снова запустим первый диалог и нажмем клавишу Назад (Back). Смотрим лог:

Сработал onCancel – диалог был отменен, и onDismiss – диалог закрылся.

Если мы будем поворачивать экран, то каждый раз будет отрабатывать onDismiss, но диалог снова будет отображен после поворота.

Запустим второй диалог – нажмем кнопку Dialog 2.

Отобразился стандартный сконструированный нами диалог. Жмем, например, No – диалог закрылся. В логах:

Dialog 2: No
Dialog 2: onDismiss

Снова запустим второй диалог и нажмем Назад. В логах:

Все так же, как и в первом случае.

Еще несколько слов по теме.

Если вы не хотите, чтобы ваш диалог можно было закрыть кнопкой, используйте для вашего диалог-фрагмента метод setCancelable с параметром false.

Есть еще один вариант вызова диалога. Это метод show, но на вход он уже принимает не FragmentManager, а FragmentTransaction. В этом случае система также сама вызовет commit внутри show, но мы можем предварительно поместить в созданную нами транзакцию какие-либо еще операции или отправить ее в BackStack.

Вы можете использовать диалог-фрагменты, как обычные фрагменты и отображать их на Activity, а не в виде диалога. Но при этом будьте аккуратнее с использованием getDialog. Я так понял, что он возвращает null в этом случае.

Если AlertDialog.Builder вам незнаком, то посмотрите Урок 60 и несколько следующих за ним. Там достаточно подробно описано, как создавать различные диалоги.

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

Читайте также:  Просмотр камер видеонаблюдения с андроида

— работаем с PreferenceFragment
— используем Headers

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

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

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

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

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

Источник

Android DialogFragment Examples

The most flexible way to create a dialog is not by using andorid.app.Dialog class but by using DialogFragment class. Through this you get full fragment capability including the ability to observe the dialog lifecycle as well as utilize ViewModels.

What is a DialogFragment?

A DialogFragment is a fragment that displays a dialog window, floating on top of its activity’s window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment’s state.

In this class we use the support dialogfragment since the framework android.app.dialogFragment was deprecated in API level 28.

Our implementation will override this class and implement
the onCreateView(LayoutInflater, ViewGroup, Bundle) to supply the content of the dialog. Alternatively, we can override onCreateDialog(Bundle) to create an entirely custom dialog, such as an AlertDialog, with its own content.

In this article we will be learning the following:

  1. Creating a dialog with ListView in kotlin.
  2. Using DialogFragment to create dialog with custom layoutt such as alertdialogs, input dialogs etc.
  3. Creating popup menus

(a). Kotlin Android DialogFragment with ListView

Kotlin Android DialogFragment with ListView tutorial.

We want to see how to open a DialogFragment when a simple button is clicked. The dialogFragment will comprise of a title and a listview.

We infact inflate it via the LayoutInflater class from an xml layout specification.

When the user clicks a ListView item we show it in a Toast. When the user clicks outside the DialogFragment, we dismiss it(the DialogFragment).

Video Tutorial

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel. Basically we have a TV for programming where do daily tutorials especially android.

Kotlin Android DialogFragment with Simple ListView

Let’s look at a complete example.

Tools

  1. IDE: Android Studio – android’s offical android IDE supported by Jetbrains and Google.
  2. Language : Kotlin -Statically Typed Language first developed by Jetbrains.
  3. Emulator : Nox Player – An emulator fast enough for my slow machine.

Gradle Scripts

We start by exploring our gradle scripts.

(a). build.gradle(App)

Here’s our app level build.gradle file. We have the dependencies DSL where we add our dependencies.

This file is called app level build.gradle since it’s located in the app folder of the project.

If you are using Android Studio version 3 and above use implementation keyword while if you are using a version less than 3 then still use the compile keyword.

Once you’ve modified this build.gradle file you have to sync your project. Android Studio will indeed prompt you to do so.

You can also see that we have started by applying two kotlin-specific plugins in our build.gradle file:

that is kotlin-android and kotlin-android-extensions .

Kotlin Code

Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.

In this class we are using Kotlin programming language.

We will have these classes in our project.

(a). PioneersFragment.kt

Represents our FragmentDialog and will infact derive from it.

1. Creating a DialogFragment

We start by creating a Kotlin class that derives from android.support.v4.app.DialogFragment . We use the support library fragment since android.app.DialogFragment is deprecated.

Note that the above statement has included a default empty constructor for our DialogFragment . We do this using the brackets( () ) in Kotlin.

2. Overriding DialogFragment’s OnCreateView()

Читайте также:  Мастер очистки кэша для андроид

We will then override the onCreateView() method of the Fragment class.

We’ve passed three parameters:

  1. LayoutInflater object.
  2. ViewGroup object.
  3. Bundle object.

3. Inflating a Layout into a DialogFragment

Inside the method first we inflate the R.layout.fraglayout layout via the inflate method, using the LayoutInflater instance.

4. Creating a Kotlin Array

Then create a Kotlin array using the arrayOf() method. This will act as our data source to host pioneers. This is what we will bind to the ListView which we will show in our DialogFragment.

5. Binding a ListView to Kotlin Array using ArrayAdapter

We then reference our ListView and set it’s adapter. We will use arrayadapter.

6. Setting a DialogFragment Title

We set the DialogFragment’s title using the setTitle() method, you pass a String to this method.

7. Listening to ListView’s Click events in Kotlin

Let’s say we want to show a Toast message when a ListView is clicked, showing the clicked item:

Here’s the full code of PioneersFragment class:

(c). MainActivity.kt

This is our MainActivity. It will contain a button that when clicked will show or open our DialogFragment.

1. Create an Activity in Kotlin

You just create a class, give it an identifier then make it derive from android.support.v7.app.AppCompatActivity :

2. Override the Activity’s onCreate() method

The onCreate() is a method that gets raised when our activity’s being created.

Here we call the onCreate() method of the super class . Then we use the setContentView() method to inflate our activity_main.xml :

3. Referencing Widgets in Kotlin

You can reference widgets from their respective layout using the findViewById() method of the activity.

Like we do with our button.

4. Obtain an Activity’s FragmentManager

Fragments get hosted by Activities. Hence an activity maintains a supportFragmentManager as a property.

We can obtain it this way:

5. Open/Show a Fragment

We can open a Fragment or show it. But first we have to instantiate that Fragment:

Then we can open it when the user clicks a button by invoking the show() method of the Fragment class:

Here’s the full code of the MainActivity :

Layout Resources

(a). activity_main.xml

This is our main activity’s layout. It will contain our Button which when clicked will open our DialogFragment.

This layout will get inflated into the main activity’s user interface. This will happen via the Activity’s setContentView() method which will require us to pass it the layout.

We will do so inside the onCreate() method of Activity.

We use the following elements:

(b). fraglayout.xml

Our DialogFragment layout. This layout be inflated into the user interface for our Dialog Fragment.

It will contain a simple ListView.

Value Resources

(a). colors.xml

Our material design colors:

(b). styles.xml

Our application’s style.

(b). Android DialogFragment – Show RecyclerView

This example will show a recyclerview in diaogfragment.

When the user clicks a show button we open a dialogfragment, displaying a RecyclerView on it.

Project Summary

No. File Major Responsibility
1. MyHolder.java RecyclerView ViewHolder class.
2. MyAdapter.java RecyclerView data adapter class
3. TVShowFragment.java DialogFragment class
4. MainActivity.java Activity class
5. activity_layout.xml To be inflated to MainActivity
6. content_main.xml To be included inside the activity_main.xml.We add our veiws and widgets here.
7. fraglayout.xml The layout to be inflated to our custom dialog fragment.
8. model.xml To model how each recyclerview item will appear

1. Create Basic Activity Project

  1. First create an empty project in android studio. Go to File –> New Project.
  2. Type the application name and choose the company name.
  3. Choose minimum SDK.
  4. Choose Basic activity.
  5. Click Finish.

Basic activity will have a toolbar and floating action button already added in the layout

Normally two layouts get generated with this option:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
3. MainActivity.java Class Main Activity.

In this example I used a basic activity.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

If you’ve created yours manually then register it inside the . as following, replacing the MainActivity with your activity name:

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

3. Create User Interface

Here are our layouts for this project:

activity_main.xml

  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed»

No. View/ViewGroup Package Role
1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.

content_main.xml

This layout gets included in your activity_main.xml.
You define your UI widgets right here.

fraglayout.xml

This layout will be inflated to our dialog fragment.

It will contain our RecyclerView as our adapterview:

model.xml

This will layout will be inflated into the View items for our RecyclerView.

Basically a CardView for each recyclerview item.

Contains a simple TextView:

4. Create Java Classes

Android apps are written in Java programming language so lets create some classes.

1. MyHolder.java

Our ViewHolder class.

2. MyAdapter.java

Our recyclerview adapter class:

TVShowFragment.java

This is our DialogFragment. It derives from android.app.DiloagFragment.

This class will show our RecyclerView:

4. MainActivity.java

Our MainActivity.
It will contain a button that when clicked will show our DialogFragment:

Example 2 – Android DialogFragment – ListView Search/Filter

The idea of dialogs is great because we can pop them out from nowhere. The user can then perform his thing then dismiss the dialog.

In this example we create a dialogfragment that gets displayed when a simple button is clicked from our main activity.

Our dialogfragment will contain a simple ListView and a SearchView. The ListView will contain a List of players.

The searchview can then be used to search the players from the list.

1. Our MainActivity Class

This is our main activity.

As a class it’s an activity since it derives from android.app.Activity .

No. Responsibility
1. It is our launcher and only activity.
2. It will contain a button which when clicked we show a dialogfragment.
3. It maintains a FragmentManager which helps in showing of our dialogfragment.

2. Our PlayerFragment class.

This is our PlayerFragment class.

No. Responsibility
1. Derives from android.app.DialogFragment hence making it a DialogFragment.
2. We’ll reference a ListView and SearchView here. ListView will be our adapterview while we’ll use a searchview for inputting our search terms.
3. We’ll dismiss our dialogfragment when the dismiss button is clicked.

3. Our MainActivity Layout

This is our main activity layout.

No. Responsibility
1. Contains a button that when clicked will open our dialogfragment.

4. OUR PlayerFragment Layout

This is our dialog fragment’s layout.

Here are it’s roles:

No. Responsibility
1. Define a ListView which will display of list of items.
2. Define a SearchView for searching/filtering our data.
3. Define a button for dismissing our dialogfragment.

Our Manifest

Our android manifest.xml. Our activity is registered here. report this ad

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Читайте также:  Ccleaner для андроид арк
Оцените статью