How Can I Control The Activity's Up Button From A Contained Fragment?
I'm building a pretty simple app. At it's core are 2 screens: 1) list-screen: a list of items 2) detail-screen: a detailed view of an item I used one Activity (which extends AppCom
Solution 1:
You can enable the up button each time the Detail Fragment loads, and disable it whenever any of the other Fragments load.
First define these methods in your Activity, which you can call from the Fragments in order to show/hide the up button:
publicvoidshowUpButton() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
publicvoidhideUpButton() {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
You will probably want to just enable the up button in on Resume() of the detail Fragment (MainActivity is just an example, change to the name of your Activity) .....
@OverridepublicvoidonResume() {
super.onResume();
MainActivityactivity= (MainActivity)getActivity();
if (activity != null) {
activity.showUpButton();
}
}
Then in the other Fragments:
@OverridepublicvoidonResume() {
super.onResume();
MainActivityactivity= (MainActivity)getActivity();
if (activity != null) {
activity.hideUpButton();
}
}
The next thing is to make the up button actually go back. First ensure that you're adding the Fragment with the up button to the back stack, and then add this to that Fragment.
@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
((MainActivity)getActivity()).onBackPressed();
returntrue;
default:
returnsuper.onOptionsItemSelected(item);
}
}
Then in the Activity, override onBackPressed() and pop from the back stack if the FragmentManager has any entries:
@OverridepublicvoidonBackPressed() {
FragmentManagerfragmentManager= getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 1) {
fragmentManager.popBackStackImmediate();
} else {
super.onBackPressed();
}
}
Post a Comment for "How Can I Control The Activity's Up Button From A Contained Fragment?"