How to use landscape and portrait layout?

59 views Asked by At

I have an activity and several fragments(they are called fragmentA and fragmentB). Now fragmentA need to have both portrait and landscape layout. fragmentB have to keep portrait. The activity shows fragmentA in onCreate method. I tryed this link:https://stackoverflow.com/a/53864286/15351040 Added following code in fragmentA.

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        activity?.let {
            it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
        }
        return super.onCreateView(inflater, container, savedInstanceState)
    }
override fun onDestroyView() {
        super.onDestroyView()
        activity?.let {
            it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }
    }

And added following code in fragmentB.

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    activity?.let {
        it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }
    return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onDestroyView() {
    super.onDestroyView()
    activity?.let {
        it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
    }
}

But when I open fragmentB, fragmentA is opened again instead of fragmentB. Maybe the onCreate of activity is called when its requestOrientation is changed. It works well when fragmentA is portrait, but not in landscape.

What should I do now?

2

There are 2 answers

1
welcomeworld On

Add configChanges tag with orientation value for activity in AndroidManifest.xml. For example:

        <activity
            android:name=".ui.activity.MainActivity"
            android:configChanges="keyboardHidden|orientation|screenSize|screenLayout" />
0
Rahul Rokade On

Used this code, I hope this code usable

public class MainActivity extends AppCompatActivity {

@SuppressLint("SourceLockedOrientationActivity")
@Override
protected void onCreate(Bundle savedInstanceState) {
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC)){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}}

And attribute provide in manifest file, all screen

android:screenOrientation="fullSensor"
        android:windowSoftInputMode="adjustResize|stateHidden"