Android : Return to previous fragment on back press

前端 未结 5 1362
南笙
南笙 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

    Update your Activity#onBackPressed() method to:

    @Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }
    

    The reason your implementation doesn't work is because the method FragmentManager#popBackStack() is asynchronous and does not happen right after it is called.

    From the documentation:

    This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.

    Reference: http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack(java.lang.String,%20int)

提交回复
热议问题