Enable display orientation changes when certain fragments are visible and off when others

I use fragments in my application. Most fragments should have only one orientation - portait. Thus, I force the activity of the holder always in portrait mode.

But one of my fragments should have both portrait and landscape modes. How to enable orientation change for only one fragment? Or do I need to do this as a separate action to handle orientation without depending on other fragments?

+5
source share
4 answers

You will need to do this manually.

1) add this line to your android activity tag: configChanges = "orientation | screenSize"

2) fragmtn activity

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

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

//Your fragment animation layout changing code

}
+2

:

setUserVisibleHint() .

:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
Activity a = getActivity();
if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
0

Use the setRequestedOrientationMode of Action when you choose which section to display.

public class MyActivity extends Activity {
  // ...

  public void chooseFragment(int x) {
    Fragment newFragment;
    if (x == 1) {
      // FragmentOne can be any orientation
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
      newFragment = new FragmentOne();
    }
    else {
      // FragmentTwo can be only portrait orientation
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      newFragment = new FragmentTwo();
    }
    getSupportFragmentManager().beginTransaction()
      .replace(R.id.fragment_container, newFragment)
      .commit();
  }

  // ...
}
0
source

In AndroidManifest.xml add android: screenOrientation = "portrait" in the fragment u that you want to fix as a Portrait , and do not add this operator to the fragment that you do not want to fix. Example:

<activity
android:name="com.example.myapp.MainActivity"
android:screenOrientation="portrait"/>
-2
source

All Articles