Programmatically enabling/disabling screen rotations in Android

主宰稳场 提交于 2019-12-03 11:06:31
iandisme

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.

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

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