我正在检查复选框的状态。我正在使用下面的代码。当应用程序启动时(复选框未选中),toast 消息显示“未选中”。但是当我打开另一个屏幕然后返回时,它不再说了。怎么做? 部分代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cb1 = (CheckBox) findViewById(R.id.CheckBox01);
if (cb1.isChecked())
{
Toast.makeText(main.this, "checked", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(main.this, "NOT checked", Toast.LENGTH_SHORT).show();
}
在这段代码中我还有一个
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
//blablabla
}
});
我在用户单击复选框时检查复选框状态的部分。
我想在每次显示此屏幕时检查复选框的状态。
最佳答案
使用 onResume()
而不是 onCreate()
。
here你可以看到activity的生命周期图,onCreate()
只被调用一次,在activity生命周期的开始...onResume()
另一方面是调用每个 Activity 回到前面的时间。
但是,OnCheckedChangeListener
内容应该在 onCreate()
或 onStart()
中声明,因为它将持续存在。
关于Android复选框状态检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4839054/