Navigation view handle back button on fragment

2019-09-03 03:28发布

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条回答
地球回转人心会变
2楼-- · 2019-09-03 04:10

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);
}
查看更多
登录 后发表回答