Android 4.2: back stack behaviour with nested fragments

后端 未结 17 1799
爱一瞬间的悲伤
爱一瞬间的悲伤 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:37

    I have implemented it correctly if anybody didnt found any answer till now

    just add this method on your child nested fragment

       @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        // This callback will only be called when MyFragment is at least Started.
        OnBackPressedCallback callback = new OnBackPressedCallback(true ) {
            @Override
            public void handleOnBackPressed() {
                // Handle the back button event
                FragmentManager fm= getFragmentManager();
                if (fm != null) {
                    if (fm.getBackStackEntryCount() > 0) {
                        fm.popBackStack();
                        Log.e( "Frag","back" );
    
                    }
    
                    List fragList = fm.getFragments();
                    if (fragList != null && fragList.size() > 0) {
                        for (Fragment frag : fragList) {
                            if (frag == null) {
                                continue;
                            }
                            if (frag.isVisible()) {
                              Log.e( "Frag","Visible" );
                            }
                        }
                    }
                }
    
    
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
        super.onCreate( savedInstanceState );
    }
    

提交回复
热议问题