Reputation: 61
In my app, MainActivity uses a navigation drawer to host several fragments. MainActivity provides the toolbar, and fragment content is displayed beneath the toolbar in a Frame Layout.
In MainActivity, I start my first fragment and initialize my toolbar as shown below.
fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Fragment 1");
One of my fragments needs a subfragment. I would like to add a back button to that subfragment, and override onBackPressed() within MainActivity.
My toolbar currently only shows the 3-line hamburger, which when pressed opens Navigation Drawer and shows a list of my fragments.
I'm not sure how to show a back arrow in my subfragment instead of a hamburger. Then I need to catch the onBackPressed() event and handle it.
I may be doing this incorrectly, and might should use activities instead of fragments, but if I do, I won't be able to animate fragment slide_in / slide_out transitions. The toolbar would slide along with the Frame Layout and I don't want that.
I would like the fragment content to show a transition, while the toolbar remains in place. Just as you would expect in a View Pager.
I would appreciate any suggestions.
Thanks!
Upvotes: 1
Views: 532
Reputation: 771
You can change your "home icon" calling those lines:
getSupportActionBar().setHomeAsUpIndicator(R.drawable.your_arrow_icon);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
For handling the "home click" your must override the onOptionsItemSelected and handle the click listener for the home MenuItem (android.R.id.home).
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Good luck!
Upvotes: 1