您应该使用 anonCheckedChangeListener
来正确监听CheckBox
更改。
我重写了您的活动以实现这些并正确设置onClick
您的按钮。删除 XML 文件中的 onClick 声明
public class MainActivity extends Activity implements OnCheckedChangeListener
{
private CheckBox chkAndroid, chkIphone, chkWindows;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chkAndroid = (CheckBox) findViewById(R.id.checkBox_android);
chkAndroid.setOnCheckedChangeListener(this);
chkIphone = (CheckBox) findViewById(R.id.checkBox_ios);
chkIphone.setOnCheckedChangeListener(this);
chkWindows = (CheckBox) findViewById(R.id.checkBox_windows);
chkWindows.setOnCheckedChangeListener(this);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
StringBuffer string = new StringBuffer();
string.append("Iphone checked: ").append(chkIphone.isChecked());
string.append("\nAndroid checked: ").append(chkAndroid.isChecked());
string.append("\nWindows checked: ").append(chkWindows.isChecked());
Toast.makeText(getApplicationContext(), string.toString(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (buttonView == chkAndroid) {
// do whatever.. you aren't doing anything currently
} else if (buttonView == chkIphone && isChecked) {
displaySuggestion();
} else if (buttonView == chkWindows && isChecked) {
displaySuggestion();
}
}
private void displaySuggestion()
{
Toast.makeText(getApplicationContext(), "Try android", Toast.LENGTH_SHORT).show();
}
}