Android 4.2: back stack behaviour with nested fragments

后端 未结 17 1802
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  春和景丽
    2020-11-29 16:39

    i was able to handle fragment back stack by adding to the parent fragment this method at the onCreate View() method and passing the root view.

    private void catchBackEvent(View v){
        v.setFocusableInTouchMode(true);
        v.requestFocus();
        v.setOnKeyListener( new OnKeyListener()
        {
            @Override
            public boolean onKey( View v, int keyCode, KeyEvent event )
            {
                if( keyCode == KeyEvent.KEYCODE_BACK )
                {
                    if(isEnableFragmentBackStack()){
                        getChildFragmentManager().popBackStack();
                                        setEnableFragmentBackStack(false);
                        return true;
                    }
                    else
                        return false;   
                }
                return false;
            }
        } );
    }
    

    The method isEnableFragmentBackStack() is a boolean flag to know when i'm on the main fragment or the next one.

    Make sure that when you commit the fragment that needs to be have stack, then you must add the addToBackstack Method.

提交回复
热议问题