Android 4.2: back stack behaviour with nested fragments

后端 未结 17 1817
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 16:01

With Android 4.2, the support library got support for nested fragments see here. I\'ve played around with it and found an interesting behaviour / bug regarding back stack an

17条回答
  •  Happy的楠姐
    2020-11-29 16:32

    If you have a DialogFragment which in turn has nested fragments, the 'workaround' is a bit different. Instead of setting an onKeyListener to the rootView, you'll need to do that with the Dialog. Also you will be setting up a DialogInterface.OnKeyListener and not the View one. Of course, remember addToBackStack!

    Btw, having 1 fragment on the backstack for delegating the call back to the activity is my personal use case. Typical scenarios might be for the count to be 0.

    Here's what you gotta do within the onCreateDialog

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Dialog dialog =  super.onCreateDialog(savedInstanceState);
            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if(keyCode == KeyEvent.KEYCODE_BACK){
                        FragmentManager cfm = getChildFragmentManager();
                        if(cfm.getBackStackEntryCount()>1){
                            cfm.popBackStack();
                            return true;
                        }   
                    }   
                    return false;
                }
            });
            return dialog;
        }
    

提交回复
热议问题