且构网

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

在 Android 中以编程方式启用/禁用屏幕旋转

更新时间:2023-02-13 10:01:04

我会将我的偏好页面写入 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.