且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Android的切换方向锁定?

更新时间:2023-11-30 16:04:58

我不明白什么是与setRequestedOrientation的问题。

在SCREEN_ORIENTATION_SENSOR相结合,横向或纵向似乎你想要的,不是吗?

 如果(....)
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
否则,如果(....)
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
否则,如果(....)
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
 

I want to create checkbox in my preference Activity that allows user to toggle orientation change.

In similar questions people write only about complete orientation lock (by overriding onConfigurationChanged method or adding configChanges in AndroidManifest.xml) or orientation enforcing ( by setRequestedOrientation ).

Is there a way to toggle orientation lock?


EDIT: I've created a method that sets preferred orientation to one of three states: landscape, portrait and sensor. This method is used in conjunction with retrieving orientation getResources().getConfiguration().orientation) and saving retrieved orientation into preferences. Then in activity that needs to lock orientation I fire this method with preferred orientation from preferences.

private static void setActivityOrientation(Activity activity, int preferenceOrientation) {
    if (preferenceOrientation == Configuration.ORIENTATION_LANDSCAPE) { 
        if( activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){ 
        // You need to check if your desired orientation isn't already set because setting orientation restarts your Activity which takes long
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    } else if (preferenceOrientation == Configuration.ORIENTATION_PORTRAIT) {
        if( activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }    
    } else {
        if( activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_SENSOR){
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }
    }
}

I don't understand what is the problem with the setRequestedOrientation.

The SCREEN_ORIENTATION_SENSOR combine to landscape or portrait seem what you want, no?

if(....)
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else if(....)
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else if(....)
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);