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?
you can go back with up button like back button ;
Implement
OnBackStackChangedListener
and add this code to your Fragment Activity.I used a combination of Roger Garzon Nieto's and sohailaziz's answers. My app has a single MainActivity, and fragments A, B, C that are loaded into it. My "home" fragment (A) implements OnBackStackChangedListener, and checks the size of the backStack; if it's less than one, then it hides the UP button. Fragments B and C always load the back button (in my design, B is launched from A, and C is launched from B). The MainActivity itself just pops the backstack on UP button tap, and has methods to show/hide the button, which the fragments call:
MainActivity:
fragmentA (implements FragmentManager.OnBackStackChangedListener):
fragmentB, fragmentC:
I know this question is old, but may be someone (like me) also needs it.
If your Activity extends AppCompatActivity, you can use a simpler (two-step) solution:
1 - Whenever you add a non-home fragment just show the up button, right after commiting the fragment transaction. Like this:
2 - Then when UP button is pressed, you hide it.
That's it.
I got it. just override onOptionsItemSelected in hosting activity and popup the backstack, e.g.
Call
getActionBar().setDisplayHomeAsUpEnabled(boolean);
andgetActionBar().setHomeButtonEnabled(boolean);
inonBackStackChanged()
as explained in an answer below.If you have one parent activity and want this up button to work as a back button, you can use this code:
add this to the onCreate in your main activity class
and then add onOptionsItemSelected like so:
I generally use this all the time and seems pretty legit