我正在制作一个程序,当我按下按钮时,它会更改背景颜色,但我有一个问题,当我更改屏幕方向时,它会再次将颜色更改为预定义的颜色,我不知道如何解决这个问题...这是我的代码。
public class MainActivity extends Activity implements OnClickListener {
LinearLayout myLayout;
LinearLayout myLayout2;
// Declare UI elements
private Button firstButton, secondButton, thirdButton, fourthButton, fifthButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // Our only layout for this app is main.xml
myLayout = (LinearLayout) findViewById(R.id.myLayout);
myLayout2 = (LinearLayout) findViewById(R.id.myLayout2);
// Initialize the UI components
firstButton = (Button) findViewById(R.id.button1);
// When we creating a button and if we expect that to use for event handling we have to set the listener
firstButton.setOnClickListener(this);
secondButton = (Button) findViewById(R.id.button2);
secondButton.setOnClickListener(this);
thirdButton = (Button) findViewById(R.id.button3);
thirdButton.setOnClickListener(this);
fourthButton = (Button) findViewById(R.id.button4);
fourthButton.setOnClickListener(this);
fifthButton = (Button) findViewById(R.id.button5);
fifthButton.setOnClickListener(this);
}
}
最佳答案
问题是当方向改变时, Activity 会重新启动。有多种方法可以解决这个问题。
一种方法是使 Activity 在方向更改时不会重新启动。操作方法如下:
添加android:configChanges="orientation|screenSize"
给您<activity
标签,位于您的 AndroidManifest.xml
中,像这样:
<activity
android:name="UserIdActivity"
android:label="@string/app_name"
android:configChanges="orientation|screenSize" />
Rastikan's answer做法略有不同,但他的做法不适用于 API 12 之后的任何 API( source 和 this too )。按照我上面的方式,您实际上不需要调用 onConfiguationChanged
在您的 Activity 类(class)中。
另一种方法是使用 onSaveInstanceState(Bundle savedInstanceState)
像Rastikan做到了。
另一种方法是让 Activity 自行重新启动,然后使用 onResume()
如有必要,当 Activity 重新启动时更改背景颜色的方法。像这样:
public boolean changeColor = false;
// set changeColor to be true whenever you change the background colour
public void onResume()
{
if (changeColor) {
// change the background color
}
}
关于Android 屏幕方向改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306809/