Question

I have a button in my Apps menu, by clicking on that button the will rotate.. BUT when I close the App and reopen the App its not rotated as I did left it.

I want to store and retrieve the Orientation with SharedPreferences. I have tried many examples but non of them actually helped me.

Here is my menu code:

    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    /** Rotation */
    case R.id.menuRotate:
        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        if (preferences.getBoolean("orientation", true)) {
            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    return false;
}

I have nothing in my onCreate:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}

Thanks a lot guys in Advance

Was it helpful?

Solution

case R.id.menuRotate:
    SharedPreferences preferences = PreferenceManager
             .getDefaultSharedPreferences(this);
    Editor editor = preferences.edit();
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        editor.putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        editor.putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    editor.commit();
    break;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    SharedPreferences preferences = PreferenceManager
             .getDefaultSharedPreferences(this);
    int orientation = preferences.getInt("orientation", -1);
    if(orientation != -1){
        setRequestedOrientation(orientation);
    }

}

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top