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?
Setting the navGraph attribute of a FragmentContainerView allows you to navigate between fragments within an activity. The NavGraph editor allows you to add navigation actions and specify arguments between different destinations.
If we consider the ActionTab app it has four fragments - one for each tab view. As the use taps through the tab options the fragment transitions through the states in the lifecycle diagram -- moving say from being in focus in onResume() to hidden in onPause().
The onAttach() event occurs before the fragment's UI is created and before the fragment or its parent activity have completed initialization. Keep this in mind when we are looking at the ActionTab activity's onCreate() when it creates its fragments.
While the Activity class has a global property called menuInflater, Fragment does not have this property. The menu inflater is instead passed into onCreateOptionsMenu (). Also note that the onCreateOptionsMenu () method used with fragments doesn't require a return statement.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With