Android How to - Initialize Activity Orientation from SharedPreferences








Question

You would like to know how to Initialize Activity Orientation from SharedPreferences.

Answer

First we need to load SharedPreferences from PreferenceManager by using the activity.

Then set the Orientation for Activity by using the constant defined in ActivityInfo, for example SCREEN_ORIENTATION_LANDSCAPE.

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.preference.PreferenceManager;
//from  w  w w.j a v a 2 s  .  com
public class Main {
  public static void initialize(Activity activity) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);

    String orientation = prefs.getString("prefOrientation", "Null");
    if ("Landscape".equals(orientation)) {
      activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    } else if ("Portrait".equals(orientation)) {
      activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else {
      activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
    }
  }
}