Fragment PopBackStack

走远了吗. 提交于 2019-12-02 20:32:36

You should not add your first fragment to the backstack, as pressing the return key will just reverse the action you did. So if you replace a fragment and you press back, it will reverse the replace you did. But if you press back on an '.add()' fragmenttransaction, it will simply remove it and show you a blank page. So i think removing the first fragment from the backstack should do the trick. Try it out and let me know!

@Override
    protected void onCreate(Bundle savedBundleState) {
        super.onCreate(savedBundleState);
        setContentView(R.layout.activity_base_new);

        Fragement_Home home = new Fragement_Home();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction().add(R.id.frameContent, home).commit();
    }

EXAMPLE:

So let's say you have two fragments called A & B

If you .add() fragment A to the page, and "addToBackStack()" ( = save reverse of the action ) you will have saved the REMOVE fragment A as action when you click on back.

If you .replace() fragment A by fragment B, and also "addToBackStack()" you will have saved the remove B and add A as action when you click on back.

So you see why it's not good practice to add your first fragmenttransaction to the backstack? It will just result in removing fragment A by pressing back, resulting in a blank page. Hope this is enough info.

Also, once you have removed the addToBackStack() to your first fragment, you don't need to override onBackPressed() because it will work how it is supposed to. It will just finish the activity when there is nothing left in the backstack without showing you that blank page first.

Your line:

if(fm.getBackStackEntryCount() > 1){

should be:

if (fm.getBackStackEntryCount() > 0) {

You are putting 3 fragments on the backstack. After you pop the first two entries off, the count of entries on the backstack then equals 1. So you prevent yourself from retrieving the first fragment you added to the backstack.

you are using this manager.beginTransaction().add(R.id.frameContent, home).addToBackStack("home").commit();

try to use this instead manager.beginTransaction().replace(R.id.frameContent, home).addToBackStack("home").commit();

Let me know if it works for u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!