2013-05-17 51 views
0

在Android中,此代碼是否驗證複選框被單擊以取消選中?如何驗證複選框即將被取消選中?

 public void onClick(View v) { 

     if (((CheckBox) v).isChecked()) { 
      Toast.makeText(IdentifyActivity.this, "clicked to check", Toast.LENGTH_LONG); 
     } 
     else{ 
      Toast.makeText(IdentifyActivity.this, "clicked to uncheck", Toast.LENGTH_LONG); 
     } 

回答

4

您可以使用OnCheckedChangeListener。你必須實現回調

onCheckedChanged(CompoundButton buttonView, boolean isChecked) 

這就是你的任務通常完成的方式。您的代碼工作,以及和可能,既approces之間沒有真正的區別

1
CheckBox cb = (CheckBox) findViewById(R.id.myCheckBox); 

cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){ 
    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     if (isChecked) { 
      // It's checked 
     } else { 
      // It's not checked 
     } 
    } 
}); 
1
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

    @Override 
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { 

     if(isChecked==true) 
     { 
      //your checkbox is checked 
      } 
     else 
     { 
      //your checkbox is not checked 
      } 

    } 
}