0

MainActivity inflates a fragment like this:

getSupportFragmentManager().beginTransaction()
            .replace(R.id.dashboard_fragment_container, df, TAG_DASHBOARD_FRAGMENT)
            .commit();

But when the screen orientation changes, I wish to remove(destroy) this fragment.

Any easy way to detect when the screen is about to change, so that I can remove inflated fragments?

Joon. P
  • 2,238
  • 7
  • 26
  • 53

2 Answers2

3

Try using method onConfigurationChanged(). It will detect screen orientation change.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        //remove fragment
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

Set these condition in onCreate(), because orientation change will call onCreate() method again:

if(Activity.getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT){
  getSupportFragmentManager().beginTransaction()
            .replace(R.id.dashboard_fragment_container, df, TAG_DASHBOARD_FRAGMENT)
            .commit();
}

Let me know if this works.

tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
0

Fragments usually get recreated on configuration change. If you don't want this to happen, use

setRetainInstance(true); in the Fragment's constructor

This will cause fragments to be retained during configuration change.

Docs

Now When the Activity is restarted because of a orientation change, the Android Framework recreates and adds the Fragment automatically.

if u want to remove fragment during configuration change use:

In Activity

 @Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();

    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

Also in Manifest:

<activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">

Now in onCreate() of Activity remove Fragment using:

    Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);  //your fragment
if(f == null){
    //there is no Fragment
}else{
    //It's already there remove it
    getSupportFragmentManager().beginTransaction().remove(f).commit();
}
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62