开发者

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.开发者_JS百科


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.


Best way to Handle DialogFragment with back button:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new Dialog(getActivity(), getTheme()){
        @Override
        public void onBackPressed() {
            // On backpress, do your stuff here.
        }
    };
}


Rahul Pundhir's answer works great if you aren't using the builder pattern. If you are using the Builder pattern on your dialog you can instead do this:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                .setTitle(...)
                .setPositiveButton(...)
                .setNegativeButton(...)
                .setMessage(...)
                .create();

        alertDialog.setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK 
                && event.getAction() == KeyEvent.ACTION_UP) {
                // TODO do the "back pressed" work here
                return true;
            }
            return false;
        });

        return alertDialog;
    }

This works by mimicking how the system calls onBackPressed() in the first place (ignoring the tracking and listening for ACTION_UP). See the source on Dialog

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜