我有一个主机活动和两个片段。我在活动上实现了OnBackStackChangeListener
,以便操作栏上的后退按钮提供一致的行为。我理解当屏幕方向发生变化时,活动会被销毁并重新创建,但有没有办法防止重复的片段因为orietation的变化而被添加到backstack而不会覆盖onConfigurationChanged
?因为现在后退按钮会翻阅重复的片段。
MyActivity :
public class DepartmentListActivity extends AppCompatActivity implements FragmentManager.OnBackStackChangedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(0, 0);
setContentView(R.layout.activity_department_list);
getSupportFragmentManager().addOnBackStackChangedListener(this);
DepartmentListFragment fragment = DepartmentListFragment.newInstance();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.department_list_container, fragment)
.addToBackStack("list")
.commit();
shouldDisplayHomeUp();
}
@Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
@Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
if( getSupportFragmentManager().getBackStackEntryCount()>1){
getSupportFragmentManager().popBackStack();
}else{
startActivity(new Intent(this, MainMenuActivity.class));
}
return true;
}
}
FromListAdapter:
Fragment fragment = DepartmentOverviewFragment.newInstance();
((DepartmentListActivity) context).
getSupportFragmentManager().
beginTransaction().
replace(R.id.department_list_container, fragment).addToBackStack("overview").commit();
答案 0 :(得分:4)
仅当savedInstanceState为null时才尝试添加片段。
答案 1 :(得分:0)
if (null == getSupportFragmentManager().findFragmentByTag("someTag")) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.department_list_container, fragment, "someTag")
.addToBackStack("list")
.commit();
}