如何防止在屏幕方向更改时将重复的片段添加到Backstack中

时间:2016-10-04 04:24:40

标签: android android-fragments

我有一个主机活动和两个片段。我在活动上实现了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();

2 个答案:

答案 0 :(得分:4)

仅当savedInstanceState为null时才尝试添加片段。

答案 1 :(得分:0)

if (null == getSupportFragmentManager().findFragmentByTag("someTag")) {
getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.department_list_container, fragment, "someTag")
    .addToBackStack("list")
    .commit();
}