Programmatically enabling/disabling screen rotations in Android

家住魔仙堡 提交于 2019-12-04 18:40:13

问题


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"

in the manifest.

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

What would be my best approach?


回答1:


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.

For example:

    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);
    }

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.

Edit:

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.




回答2:


Add This line inside onCreate() Function. It is working ...

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


来源:https://stackoverflow.com/questions/3419239/programmatically-enabling-disabling-screen-rotations-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!