Search code examples
androidandroid-fragmentsandroid-actionbar

actionbar up navigation with fragments


I have a tabbed Actionbar/viewpager layout with three tabs say A, B, and C. In tab C tab(fragment),I am adding another fragment say fragment D. with

 DFragment f= new DFragment();
 ft.add(android.R.id.content, f, "");
 ft.remove(CFragment.this);
 ft.addToBackStack(null);
 ft.commit();

I modify actionbar in DFragment's onResume to add up button:

ActionBar ab = getActivity().getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayShowHomeEnabled(true);

Now in DFragment, when I press hardware(phone) Back button, I return to the original Tabbed(ABC) layout with CFragment selected. How can I achieve this functionality with actionbar up button?


Solution

  • Implement OnBackStackChangedListener and add this code to your Fragment Activity.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //Listen for changes in the back stack
        getSupportFragmentManager().addOnBackStackChangedListener(this);
        //Handle when activity is recreated like on orientation Change
        shouldDisplayHomeUp();
    }
    
    @Override
    public void onBackStackChanged() {
        shouldDisplayHomeUp();
    }
    
    public void shouldDisplayHomeUp(){
       //Enable Up button only  if there are entries in the back stack
       boolean canGoBack = getSupportFragmentManager().getBackStackEntryCount()>0;
       getSupportActionBar().setDisplayHomeAsUpEnabled(canGoBack);
    }
    
    @Override
    public boolean onSupportNavigateUp() {
        //This method is called when the up button is pressed. Just the pop back stack.
        getSupportFragmentManager().popBackStack();
        return true;
    }