我使用 onBackPressed() 在 MainActivity(有很多片段)中的 Back 按钮上实现了 backstack 导航。我想在按下向上按钮时实现相同的后台导航。问题是我只想要一个片段中的向上按钮,但是当我在所需片段上按下向上按钮时,向上按钮出现在每个片段上。甚至 setDisplayHomeAsEnabled(false) 也不起作用。如何仅在一个片段中有向上按钮?
Desired Fragment:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Main Activity
public class HomePage extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
if (findViewById(R.id.fragment_place) != null) {
if (savedInstanceState != null) {
return;
}
HomeFrag firstFragment = new HomeFrag();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_place, firstFragment).commit();
}
}
/* @Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
} */
public void selectFrag(View view) {
Fragment fr = null;
if (view == findViewById(R.id.home_btn)) {
fr = new HomeFrag();
} else if (view == findViewById(R.id.search_btn)) {
fr = new SearchFrag();
} else if (view == findViewById(R.id.log_btn)) {
fr = new LogFrag();
} else if (view == findViewById(R.id.events_btn)) {
fr = new EventFrag();
} else if (view == findViewById(R.id.profile_btn)) {
fr = new ProfileFrag();
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr).addToBackStack(null);
fragmentTransaction.commit();
}
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0)
getFragmentManager().popBackStack();
else
super.onBackPressed();
}
}