在 Android 中以编程方式启用/禁用屏幕旋转 [英] Programmatically enabling/disabling screen rotations in Android

查看:79
本文介绍了在 Android 中以编程方式启用/禁用屏幕旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用,可以显示大量文本供用户阅读.

I have an app which displays a large amount of text for the user to read.

我发现躺着阅读时,即使我的头和屏幕对齐,我也会对屏幕旋转感到恼火.

I've found that when reading while lying down, I get annoyed that the screen rotates even though my head and the screen are aligned.

我不想将其设置为永久处于纵向模式,因此我认为这会排除设置

I do not want to set this to be permanently in portrait mode, so I think this would preclude an approach of setting the

 android:screenOrientation="portrait"

在清单中.

理想情况下,我想通过首选项页面启用/禁用自动方向更改.

Ideally, I would like to enable/disable automatic orientation changes via a preference page.

我最好的方法是什么?

推荐答案

我会将我的偏好页面写入 SharedPreferences 用于我的应用程序,然后读取此值并调用 Activity.setRequestedOrientation() 加载或显示相关文本视图时的代码.

I would do this by having my preference page write to the SharedPreferences for my application, then reading this value and calling Activity.setRequestedOrientation() from the code when the text view in question is loaded or displayed.

例如:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.getBoolean("fix_orientation_to_portrait", false)) {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }

这可以在 onCreate()onResume() 方法中.不在 onCreate() 方法中使用它的唯一原因是如果设置的更改发生在此活动中,或者发生在完成后将返回到此活动的子活动上.

This can be in either the onCreate() or onResume() method. The only reason not to have it in the onCreate() method is if the changing of the setting happens in this activity, or on a child activity that will come back to this one when it is done.

好的,如果这不起作用(我不确定它会起作用),也许您可​​以尝试使用两个不同的布局 xml 文件 - 一个设置了 screenOrientation,另一个没有.当您加载您的活动/视图时,您可以根据您保存的首选项动态加载一个或另一个.讨厌不干净,但它应该可以工作.

OK, if that doesn't work (and I am not really sure it will), maybe you could try having two different layout xml files - one with the screenOrientation set, and the other without. When you load your Activity/View, you can dynamically load one or the other based on your saved preferences. It's nasty not clean, but it should work.

这篇关于在 Android 中以编程方式启用/禁用屏幕旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆