简体   繁体   English

如何在android中切换方向锁?

[英]How to toggle orientation lock in android?

I want to create checkbox in my preference Activity that allows user to toggle orientation change. 我想在我的偏好Activity中创建复选框,允许用户切换方向更改。

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 ). 在类似的问题中,人们只编写完整的方向锁(通过覆盖onConfigurationChanged方法或在AndroidManifest.xml中添加configChanges)或方向强制(通过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. 此方法与检索方向getResources().getConfiguration().orientation)结合使用,并将检索到的方向保存到首选项中。 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. 我不明白setRequestedOrientation有什么问题。

The SCREEN_ORIENTATION_SENSOR combine to landscape or portrait seem what you want, no? SCREEN_ORIENTATION_SENSOR结合到风景或肖像似乎你想要的,不是吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM