Navigation drawer, handling the back button to go to previous fragments?

后端 未结 6 1668
陌清茗
陌清茗 2020-12-02 14:45

I\'m using the built-in navigation drawer to run my app. I can\'t quite figure out how to handle the back button. When it\'s pressed I want it to load the very first fragmen

6条回答
  •  一整个雨季
    2020-12-02 15:01

    Instead of:

    fm.beginTransaction().replace(R.id.main, newFragment).addToBackStack("fragBack").commit();
    

    Call:

    fm.beginTransaction().add(R.id.main, newFragment).addToBackStack("fragBack").commit();
    

    addToBackStack works with add.

    replace function removes previous fragment and places new fragment so on your back-stack there is only one fragment all the time. So use add function to keep previous fragments on stack.

    To always goto fragemnt1 from any fragment onBackPress try to do following:

    getFragmentManager().popBackStack();
    fm.beginTransaction().add(R.id.main, newFragment).addToBackStack("fragBack").commit();
    

    this will remove last transaction from backstack and add new one. Try this.

提交回复
热议问题