Implementing proper back navigation and home button handling using Toolbar in Android

前端 未结 6 1824
粉色の甜心
粉色の甜心 2021-01-30 23:31

I am using a single activity and multiple fragments(screenshot attached) within the same activity to provide a seamless navigation. But after implementing the latest toolbar and

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 00:13

    Add this in your MainActivity where you are calling Fragments. getBackStackEntryCount() Return number of fragments in the back stack. where the fragment on the bottom of the stack has index 0. popBackStack() Pop the top Fragment off the back stack

     @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
    
            if (id == android.R.id.home) {
                if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                    getSupportFragmentManager().popBackStack();
                } else {
                    super.onBackPressed();
                }
            }
            return true;
        }
    

    And in your Fragment where you want to go back use this function

      @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                getActivity().onBackPressed();
            }
            return true;
        }
    

提交回复
热议问题