我有一个活动,其中包含诸如ImageView,Switch,EditText,TextView之类的元素,当更改屏幕方向时,某些元素使我返回到其初始值,以解决该问题时使用onSaveInstanceState和onRestoreInstanceState来存储和检索信息。屏幕方向。除了一个Toast的一个细节外,它似乎工作正常。
我有一个名为dateOfNotification的TextView,它显示用户选择的日期,它以visibility = "gone"
开头,还有一个带有以下代码的Switch:
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(switch1.isChecked()){
if(dateOfNotification.getVisibility() == View.VISIBLE){
hour.setText("08:00");
}
else{
Toast.makeText(tareas.this, "First enter a date", Toast.LENGTH_SHORT).show();
switch1.setChecked(false);
}
}
}
});
这里要注意的重要一点是,如果dateOfNotification不存在,则无法激活switch1。
现在可以在不丢失数据的情况下更改屏幕方向:
protected void onSaveInstanceState( final Bundle outState ) {
super.onSaveInstanceState(outState);
outState.putInt("visDate", dateOfNotification.getVisibility());
outState.putBoolean("statusSW1", switch1.isChecked());
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
dateOfNotification.setVisibility(savedInstanceState.getInt("visDate"));
switch1.setChecked(savedInstanceState.getBoolean("statusSW1"));
}
问题是:
当dateOfNotification是可见的并且switch1被选中并且我改变方向时,值仍然是dateOfNotification是可见的并且switch1被选中,但是我不知道为什么Toast“首次输入日期”向我显示,假定当dateOfNotification时是可见的,不应该显示Toast,更罕见的是,为了显示Toast,dateOfNotification被认为是隐藏的,但是为什么开关不能禁用我呢?
else{
Toast.makeText(tareas.this, "First enter a date", Toast.LENGTH_SHORT).show();
switch1.setChecked(false);
}
在我看来,仅执行Toast.makeText(tareas.this, "First enter a date", Toast.LENGTH_SHORT).show();
而没有执行switch1.setChecked(false);
编辑
通过测试,我了解发生了什么,无论是否有onSaveInstanceState都始终保存switch1的状态,然后在旋转屏幕dateOfNotification为Gone时,但是当setOnCheckedChangeListener看到switch1已激活时,将检索并激活switch1的状态隐藏了dateOfNotification,然后显示Toast并关闭了switch1,然后使用onRestoreInstanceState恢复了dateOfNotification的可见性和switch1的状态,然后再次将其激活。
所以我想知道是否有某种方法可以使旋转屏幕时不自动加载switch1的状态,该状态只能通过onRestoreInstanceState加载