Search code examples
androidandroid-fragmentsandroid-toolbarandroid-navigation

back button navigation with fragments


I'm building a somewhat gallery app. I use one activity to hold fragment_1 in which I display images in a recyclerview. From fragment_1 I can go to fragment_2. Both fragments have their own different toolbars. My wish is to go from fragment_2 back to fragment_1 by pressing a back arrow in the toolbar.

How I go from fragment_1 to fragment_2:

Fragment2 fragment2 = new Fragment2();
    getActivity().getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, fragment2)
            .addToBackStack(null).commit();

What I already did in fragment_2:

Toolbar toolbar = getView().findViewById(R.id.toolbar_2);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

This didn't work:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            getActivity().onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Solution

  • If you want onOptionsItemSelected to be triggerd from a fragment you need to set setHasOptionsMenu to true, for example from onViewCreated :

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
       setHasOptionsMenu(true);
    }