我结合了Roger Garzon Nieto和sohailaziz的答案。我的应用程序只有一个MainActivity,并且片段A,B,C已加载到其中。我的“ home”片段(A)实现了OnBackStackChangedListener,并检查backStack的大小;如果小于1,则隐藏UP按钮。片段B和C总是加载后退按钮(在我的设计中,B从A启动,而C从B启动)。MainActivity本身只是在按下UP按钮时弹出后退堆栈,并具有显示/隐藏按钮的方法,这些片段称为:
主要活动:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
getSupportFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
public void showUpButton() { getSupportActionBar().setDisplayHomeAsUpEnabled(true); }
public void hideUpButton() { getSupportActionBar().setDisplayHomeAsUpEnabled(false); }
fragmentA(实现FragmentManager.OnBackStackChangedListener):
public void onCreate(Bundle savedinstanceSate) {
// listen to backstack changes
getActivity().getSupportFragmentManager().addOnBackStackChangedListener(this);
// other fragment init stuff
...
}
public void onBackStackChanged() {
// enable Up button only if there are entries on the backstack
if(getActivity().getSupportFragmentManager().getBackStackEntryCount() < 1) {
((MainActivity)getActivity()).hideUpButton();
}
}
片段B,片段C:
public void onCreate(Bundle savedinstanceSate) {
// show the UP button
((MainActivity)getActivity()).showUpButton();
// other fragment init stuff
...
}