Disable and enable orientation changes in an activity in Android programatically

a 夏天 提交于 2019-12-04 03:35:09
ashfak

If you want to disable orientation changes of the phone then you may use this code in the manifest

<activity android:name=".class_name"

//if you want your screen in portrait

android:screenOrientation="portrait" >

//if you want you screen in landscape mode

android:screenOrientation="landscape" >

and if you want your phone to change orientation but prevent the process from restarting then you can use the onConfigurationChanged method in your class:

@Override
public void onConfigurationChanged(Configuration newConfig) {
   // ignore orientation change
   if (newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE) {
       super.onConfigurationChanged(newConfig);
   }
}

Try this..

There is no wrong in your code. It's correct i checked it. Use that code in onConfigurationChanged that may give the difference and another thing is use below code to disable the activity reset.

<activity
    android:name="YourActivity"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="adjustPan"/>  

You could override the on onConfiguratoinChanged method to disable orientation changes:

@Override
public void onConfigurationChanged(Configuration newConfig) {
   // ignore orientation change
   if (newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE) {
       super.onConfigurationChanged(newConfig);
   }
}

Do not forget to enable the orientation changed listener in your AndroidManifest.xml file:

<activity android:configChanges="orientation" >
Deep Dave

Simple: one line to add after Activity Name in android manifest

android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale

This worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!