Lock Screens rotation programmatically
suggest changeIt is very common during development to lock or unlock screen rotation for a specific stretch of code.
For instance, while a dialog with information is showing, lock the screen's rotation so the dialog stays up and the current activity is not rebuilt. Unlock rotation when the dialog is dismissed.
Rotation can be locked from the manifest:
<activity
android:name=".TheActivity"
android:screenOrientation="portrait"
android:label="@string/app_name" >
</activity>
The same lock can be applied in code. The unlock branch clears FLAG_NOT_TOUCHABLE, but the lock branch never sets that flag, so the clearFlags call has no effect in this sample:
public void lockDeviceRotation(boolean value) {
if (value) {
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
}
}
Call it to lock and unlock device rotation, respectively:
lockDeviceRotation(true);
and
lockDeviceRotation(false);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents