Android : Return to previous fragment on back press

前端 未结 5 1359
南笙
南笙 2021-02-12 17:44

I have implemented Navigation Drawer which is a subclass of Activity. I have many fragments in my application. My question goes here

Imagine there are 3 fragments :

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-12 18:36

    Here is working and tested code by me, This will help you

     private static final int TIME_INTERVAL = 2000;
    private long mBackPressed;
     private void applyExit() {
        if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
            finish();
        } else {
             Toast.makeText(this,"Press Again to exit",Toast.LENGTH_LONG).show();
        }
        mBackPressed = System.currentTimeMillis();
    }
    
    @Override
    public void onBackPressed() {
        fm = getSupportFragmentManager();
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }
        if (fm.getFragments().size() <= 1) {
            applyExit();
        } else {
            for (Fragment frag : fm.getFragments()) {
                if (frag == null) {
                    applyExit();
                    return;
                }
                if (frag.isVisible()) {
                    FragmentManager childFm = frag.getChildFragmentManager();
                    if (childFm.getFragments() == null) {
                        super.onBackPressed();
                        return;
                    }
                    if (childFm.getBackStackEntryCount() > 0) {
                        childFm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                        return;
                    } else {
                        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                        return;
                    }
                }
            }
        }
    }
    

提交回复
热议问题