BiGGZ
BiGGZ

Reputation: 503

How to prevent duplicate fragments from being added to the backstack when screen orientation changes

I have one host activity and two fragments. I've implemented OnBackStackChangeListener on the activity so that the back button on the action bar provides consistent behaviour. I understand that when screen orientation changes, an activity is destroyed and re-created, but is there any way to prevent duplicate fragments from being added to the backstack as a result of orietation changes without overriding onConfigurationChanged? Because now the back button pages through duplicate fragments.

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();

Upvotes: 0

Views: 2129

Answers (2)

user3161880
user3161880

Reputation: 1055

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

Upvotes: 0

Jayesh Elamgodil
Jayesh Elamgodil

Reputation: 1477

Try adding the fragment only if the savedInstanceState is null.

Upvotes: 4

Related Questions