Search code examples
javaandroidorientationbuttonclick

Changing orientation with onClick android


I am trying to implement a button click to be able to change the orientation of the activity however, it is going into landscape mode but not going back to portrait.

if(!state){
    setRequestedOrientation(MainActivity.SCREEN_ORIENTATION_LANDSCAPE);
}
else {
    setRequestedOrientation(MainActivity.SCREEN_ORIENTATION_PORTRAIT);
}
state = !state;

What I read was to, have state = false, when the button is pressed, change the orientation, then state is set as true, at this point if the button is pressed again the activity will change back to landscape.

I also read about using switch? But I tried implementing that but didn't go so well so I tried this method.

Edit

I've implemented using getting the surface rotation and they are able to pick up the rotation either being 0 or 90

if (orientation==Surface.ROTATION_0)
{
    Toast.makeText(getBaseContext(), "going to landscape", Toast.LENGTH_LONG).show();
    setRequestedOrientation(MainActivity.SCREEN_ORIENTATION_LANDSCAPE);
}
else if (orientation==Surface.ROTATION_90)
{
    Toast.makeText(getBaseContext(), "going to portrait", Toast.LENGTH_LONG).show();
    setRequestedOrientation(MainActivity.SCREEN_ORIENTATION_PORTRAIT);
}

However, as the activity goes into landscape and the toast is shown, when I try to go back into portrait the toast does show "going to portrait" but the setRequestOrientation does not execute. What seems to be the issue?


Solution

  • When an activity is rotated it is destroyed and re-created. When this happens you are going to be losing the value of 'state'. This will result in you never hitting the other option as it is always being returned back to the original option.

    Look at onSaveInstanceState() HERE.

    You can then access the bundle in the onCreate() method to retrieve the value.