Navigation view handle back button on fragment

女生的网名这么多〃 提交于 2019-12-12 06:37:18

问题


Hi I need to handle back button on fragment. I using this navigation on my mobile apps. The question is how to handle back button when I open new fragment page?

I try using below code on new fragment.

  actionBar.setDisplayShowHomeEnabled(true);
  actionBar.setDisplayHomeAsUpEnabled(true);

But when click the back button , the navigation will be open. Any solution ?

Thanks


回答1:


As you know whenever user presses Back button you need to go to the previously loaded fragment and to do that try this (note fragment must be added with transaction.addToBackStack(null);)

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == android.R.id.home) {
        int backStackCount = fragmentManager.getBackStackEntryCount();//check currently how many frags loaded
        if (backStackCount > 0) {
            fragmentManager.popBackStack(); //go back to previously loaded fragment
        }   
    }

    return super.onOptionsItemSelected(item);
}


来源:https://stackoverflow.com/questions/37499573/navigation-view-handle-back-button-on-fragment

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