Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DialogFragment and back button

Is there any possibility to intercept the key button in DialogFragment? sorry for the naive question.. the onBackPressed of my FragmentActivity is never called.

thanks in advance

    if (imageFile.exists()) {             ShowPicDialog newFragment = ShowPicDialog.newInstance();             FragmentTransaction ft = manager.beginTransaction();             Fragment prev = manager.findFragmentByTag("picDialog");             if (prev != null) {                 ft.remove(prev);             }              ft.addToBackStack("picDialog");             newFragment.getArguments().putString("path", imageFile.getAbsolutePath());             newFragment.show(ft, "picDialog");         } 

sorry I added the snip of code I use to show the dialog.

like image 516
Blackbelt Avatar asked Oct 01 '11 18:10

Blackbelt


People also ask

Is DialogFragment deprecated?

This class was deprecated in API level 28. Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle.

What is the difference between dialog & DialogFragment?

Dialog: A dialog is a small window that prompts the user to make a decision or enter additional information. DialogFragment: A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.

What is a DialogFragment?

Android DialogFragments. DialogFragment is a utility class which extends the Fragment class. It is a part of the v4 support library and is used to display an overlay modal window within an activity that floats on top of the rest of the content. Essentially a DialogFragment displays a Dialog but inside a Fragment.

How do I destroy DialogFragment?

tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog. Dismiss the fragment and its dialog.


1 Answers

It's hard to say for sure what the issue is, since you haven't posted any code. But my first guess is that you haven't added the DialogFragment to the back stack by calling the addToBackStack method of the FragmentTransaction that you're using to add your fragment to the activity.

There are examples right in the Android documentation pages that give examples of a good pattern for using a DialogFragment in your Activity.

Since you are displaying a Dialog, the created Dialog will receive the key events, not the parent Activity. So, set a Dialog.OnKeyListener when you create the Dialog's fragment, and call setCancelable(false) on the Dialog to prevent the back key from dismissing it. You can then handle the back key in your OnKeyListener's onkey method.

like image 120
Jason LeBrun Avatar answered Oct 04 '22 13:10

Jason LeBrun