0

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?

4

1 回答 1

0

当一个活动被旋转时,它被销毁并重新创建。当这种情况发生时,您将失去“状态”的价值。这将导致您永远不会点击其他选项,因为它总是返回到原始选项。

在这里查看 onSaveInstanceState() 。

然后,您可以在 onCreate() 方法中访问包以检索该值。

于 2013-08-15T10:13:05.067 回答