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?
Add configChanges tag with orientation value for activity in AndroidManifest.xml. For example: