您應該使用onCheckedChangeListener
來正確地偵聽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();
}
}
你爲什麼不發佈您的代碼,所以我們沒有從你的回購中檢查出來?它會讓生活更輕鬆 – dymmeh
鏈接到文件:https://code.google.com/p/my-android-ui-examples/source/browse/CheckBoxExample/src/com/sudipta/checkbox/MainActivity.java – dymmeh
鏈接是現在死了這就是爲什麼你應該下次發佈你的代碼 – amorenew