Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically enabling/disabling screen rotations in 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"

in the manifest.

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

What would be my best approach?

like image 536
jamesh Avatar asked Aug 05 '10 21:08

jamesh


2 Answers

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

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
like image 169
Irshad Khan Avatar answered Sep 28 '22 12:09

Irshad Khan


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.

like image 45
iandisme Avatar answered Sep 28 '22 11:09

iandisme