首先,我对这个 android 编程还很陌生。我想问一下,为什么当我启动我的应用程序时我的开关总是打开。当我将其关闭并转到另一个 Activity 并返回到第一个 Activity 时,开关按钮再次打开 任何线索? 我试过 Android ToggleButton always check但我还是不明白。
switchStatus = (TextView) findViewById(R.id.View1);
mySwitch.setChecked(true);
mySwitch = (Switch) findViewById(R.id.switch1);
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(mySwitch.isChecked()){
mySwitch.setChecked(true);
switchStatus.setText("Switch is currently On");
onResume();
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
}
});
}
else{
mySwitch.setChecked(false);
switchStatus.setText("Switch is currently OFF");
onPause();
}
}
});
最佳答案
开关状态丢失,因为离开时Activity被销毁。所以你应该考虑保存 mySwitch 的状态。您可以使用 SharedPreferences 来完成此操作,或者...
you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
关于android - 开关按钮始终打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27814980/