Android dialogfragment dismiss listener

OnDismissListener в DialogFragment

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

Я использую код из первого ответа на этот вопрос stackru, но эта часть кода не работает, потому что у меня есть фрагмент, а не действие. Метод onDismiss вызывается в dialogfragment, но оператор if не выполняется и поэтому не вызывает фрагмент. Я пытался заменить эту часть с getFragmentManager и getParentFragment и get / setTargetFragment, но это не работает.

Кто-нибудь может мне помочь, пожалуйста?

3 ответа

Это старая проблема, но я не нашел решения, которым я доволен. Я не люблю передавать прослушиватели на мой DialogFragment или устанавливать TargetFragment, потому что это может нарушить изменение ориентации. Что Вы думаете об этом?

Я думаю, что вы можете еще один способ заархивировать его:

тогда вы можете позвонить yourfragment.myDissmiss() в вашем public void onDismiss(final DialogInterface dialog) из DialogFragmentImage ,

Вы можете попробовать перезвонить интерфейс,

создать интерфейс в вашем фрагменте диалога

реализовать это в вашем фрагменте,

Теперь в вашем диалоговом фрагменте получите объект вашего родительского фрагмента, например:

Вы должны вызвать этот метод из вашего фрагмента, чтобы установить слушателя.

Теперь в вашем методе onDismiss() вашего диалогового фрагмента вызовите onDismiss, используя эту ссылку

Источник

Lifecycle-Aware Interactor for DialogFragment

Here’s a problem: show a DialogFragment , then listen for its events. What would you do?

This article will help you create a foolproof mechanism to listen, even sending signals, to DialogFragment while considering any Android lifecycles within.

You might want to read about Android Architecture Component before moving on because this article is heavily depended on components in it.

😕 Problem

Most of the time, listening for events inside DialogFragment is not a trivial task. There are things to consider:

  1. A listener can be an Activity or a Fragment , depending on which one is currently showing the Dialog . Therefore, writing code to inform listener on events should be as flexible as possible, as the listener may come from different types.
  2. Reference to the listener should also be brought across config changes, as every Android app is highly prone to these changes: orientation, language, and such.
  3. Other than listening, sometimes we are required to send data to it, in order to prevent redundancy in writing business logic.

🌟 Characteristics of DialogFragment

DialogFragment is a component of Android SDK that can be used to display a Dialog while managing its lifecycle. It is preferable to use DialogFragment than Dialog , as it is as functional but safer.

There are some characteristics of DialogFragment that we need to understand before we discuss the solution for our problem:

  1. DialogFragment displays a Dialog , by invoking onCreateDialog() . The Dialog itself render a view that is defined by onCreateView() . You may override these methods to create your own Dialog .
  2. It handles created Dialog ’s lifecycle, therefore, you don’t need to clear reference to the Dialog whenever its Activity is finished.
  3. It is attached to FragmentManager of its host. It may belong to Activity , or a Fragment . Hence, dismissal of its dialog should also consider popping itself from the FragmentManager . Always use dismiss() or dismissAllowingStateLoss() to close a DialogFragment (don’t use dialog?.dismiss() )
Читайте также:  Прогород для андроида с ключом

💡 Solutions

There are 3 solutions that I propose. The third one is my choice.

Get a reference to host Activity or Fragment, then invoke the corresponding method. This can be achieved if the host has implemented the listener Interface.

Источник

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

— работаем с 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, Тестирование

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

Читайте также:  Как через обновить версию android

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

Источник

DialogFragment

java.lang.Object
android.support.v4.app.Fragment
android.support.v4.app.DialogFragment
Known Direct Subclasses
AppCompatDialogFragment A special version of DialogFragment which uses an AppCompatDialog in place of a platform-styled dialog.
MediaRouteChooserDialogFragment Media route chooser dialog fragment.
MediaRouteControllerDialogFragment Media route controller dialog fragment.
PreferenceDialogFragmentCompat

Class Overview

Static library support version of the framework’s DialogFragment . Used to write apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used; it does not try to switch to the framework’s implementation. See the framework SDK documentation for a class overview.

Summary

Constants
int STYLE_NORMAL Style for setStyle(int, int) : a basic, normal dialog.
int STYLE_NO_FRAME Style for setStyle(int, int) : don’t draw any frame at all; the view hierarchy returned by onCreateView(LayoutInflater, ViewGroup, Bundle) is entirely responsible for drawing the dialog.
int STYLE_NO_INPUT Style for setStyle(int, int) : like STYLE_NO_FRAME , but also disables all input to the dialog.
int STYLE_NO_TITLE Style for setStyle(int, int) : don’t include a title area.
Public Constructors
Public Methods

Constants

public static final int STYLE_NORMAL

Style for setStyle(int, int) : a basic, normal dialog.

public static final int STYLE_NO_FRAME

Style for setStyle(int, int) : don’t draw any frame at all; the view hierarchy returned by onCreateView(LayoutInflater, ViewGroup, Bundle) is entirely responsible for drawing the dialog.

public static final int STYLE_NO_INPUT

Style for setStyle(int, int) : like STYLE_NO_FRAME , but also disables all input to the dialog. The user can not touch it, and its window will not receive input focus.

public static final int STYLE_NO_TITLE

Style for setStyle(int, int) : don’t include a title area.

Public Constructors

public DialogFragment ()

Public Methods

public void dismiss ()

Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.

public void dismissAllowingStateLoss ()

Version of dismiss() that uses FragmentTransaction.commitAllowingStateLoss() . See linked documentation for further details.

public Dialog getDialog ()

public boolean getShowsDialog ()

Return the current value of setShowsDialog(boolean) .

public int getTheme ()

public boolean isCancelable ()

Return the current value of setCancelable(boolean) .

public void onActivityCreated (Bundle savedInstanceState)

Called when the fragment’s activity has been created and this fragment’s view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle) and before onViewStateRestored(Bundle) .

Parameters
savedInstanceState If the fragment is being re-created from a previous saved state, this is the state.

public void onAttach (Activity activity)

Called when a fragment is first attached to its activity. onCreate(Bundle) will be called after this.

public void onCancel (DialogInterface dialog)

This method will be invoked when the dialog is canceled.

Parameters
dialog The dialog that was canceled will be passed into the method.

public void onCreate (Bundle savedInstanceState)

Called to do initial creation of a fragment. This is called after onAttach(Activity) and before onCreateView(LayoutInflater, ViewGroup, Bundle) .

Note that this can be called while the fragment’s activity is still in the process of being created. As such, you can not rely on things like the activity’s content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, see onActivityCreated(Bundle) .

Parameters
savedInstanceState If the fragment is being re-created from a previous saved state, this is the state.

public Dialog onCreateDialog (Bundle savedInstanceState)

Override to build your own custom Dialog container. This is typically used to show an AlertDialog instead of a generic Dialog; when doing so, onCreateView(LayoutInflater, ViewGroup, Bundle) does not need to be implemented since the AlertDialog takes care of its own content.

This method will be called after onCreate(Bundle) and before onCreateView(LayoutInflater, ViewGroup, Bundle) . The default implementation simply instantiates and returns a Dialog class.

Note: DialogFragment own the Dialog.setOnCancelListener and Dialog.setOnDismissListener callbacks. You must not set them yourself. To find out about these events, override onCancel(DialogInterface) and onDismiss(DialogInterface) .

Parameters
savedInstanceState The last saved instance state of the Fragment, or null if this is a freshly created Fragment.
Returns
  • Return a new Dialog instance to be displayed by the Fragment.

public void onDestroyView ()

public void onDetach ()

Called when the fragment is no longer attached to its activity. This is called after onDestroy() .

public void onDismiss (DialogInterface dialog)

This method will be invoked when the dialog is dismissed.

Parameters
dialog The dialog that was dismissed will be passed into the method.

public void onSaveInstanceState (Bundle outState)

Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance of its process is restarted. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate(Bundle) , onCreateView(LayoutInflater, ViewGroup, Bundle) , and onActivityCreated(Bundle) .

This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy() . There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

Parameters
outState Bundle in which to place your saved state.

public void onStart ()

Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity’s lifecycle.

public void onStop ()

Called when the Fragment is no longer started. This is generally tied to Activity.onStop of the containing Activity’s lifecycle.

public void setCancelable (boolean cancelable)

Control whether the shown Dialog is cancelable. Use this instead of directly calling Dialog.setCancelable(boolean) , because DialogFragment needs to change its behavior based on this.

Parameters
cancelable If true, the dialog is cancelable. The default is true.

public void setShowsDialog (boolean showsDialog)

Controls whether this fragment should be shown in a dialog. If not set, no Dialog will be created in onActivityCreated(Bundle) , and the fragment’s view hierarchy will thus not be added to it. This allows you to instead use it as a normal fragment (embedded inside of its activity).

This is normally set for you based on whether the fragment is associated with a container view ID passed to FragmentTransaction.add(int, Fragment) . If the fragment was added with a container, setShowsDialog will be initialized to false; otherwise, it will be true.

Parameters
showsDialog If true, the fragment will be displayed in a Dialog. If false, no Dialog will be created and the fragment’s view hierarchly left undisturbed.

public void setStyle (int style, int theme)

Call to customize the basic appearance and behavior of the fragment’s dialog. This can be used for some common dialog behaviors, taking care of selecting flags, theme, and other options for you. The same effect can be achieve by manually setting Dialog and Window attributes yourself. Calling this after the fragment’s Dialog is created will have no effect.

Parameters
style Selects a standard style: may be STYLE_NORMAL , STYLE_NO_TITLE , STYLE_NO_FRAME , or STYLE_NO_INPUT .
theme Optional custom theme. If 0, an appropriate theme (based on the style) will be selected for you.

public void show (FragmentManager manager, String tag)

Display the dialog, adding the fragment to the given FragmentManager. This is a convenience for explicitly creating a transaction, adding the fragment to it with the given tag, and committing it. This does not add the transaction to the back stack. When the fragment is dismissed, a new transaction will be executed to remove it from the activity.

Parameters
manager The FragmentManager this fragment will be added to.
tag The tag for this fragment, as per FragmentTransaction.add .

public int show (FragmentTransaction transaction, String tag)

Display the dialog, adding the fragment using an existing transaction and then committing the transaction.

Источник

Читайте также:  Как удалить аккаунт ми фит с андроида
Оцените статью