我正在尝试在选中复选框时显示一条消息。问题是没有显示消息。如果我在默认选中框的情况下启动应用程序,则会在开头显示该消息,如果我尝试取消选中并再次检查,则不会再次出现。这是代码:
public class MainActivity extends AppCompatActivity {
CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBox = (CheckBox) findViewById(R.id.checkBox);
if (checkBox.isChecked())
Toast.makeText(MainActivity.this, "Box was checked", Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:1)
您需要为您的复选框实现一个侦听器,以便处理其点击次数。删除此行
if (checkBox.isChecked())
Toast.makeText(MainActivity.this, "Box was checked", Toast.LENGTH_SHORT).show();
并使用此代码:
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
Toast.makeText(MainActivity.this, "Box was checked", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Box was unchecked", Toast.LENGTH_SHORT).show();
}
});
答案 1 :(得分:0)
你需要在复选框上设置一个监听器。
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){})