56

我在 android 中有一个复选框,它具有以下 XML:

<CheckBox
   android:id="@+id/item_check"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:onClick="itemClicked" />

这是我的 Activity 类中的 onClick() 方法。

public void itemClicked(View v) {
  //code to check if this checkbox is checked!
}

我知道我们可以创建复选框的对象并为其分配 id。onClick但是在通过 XML声明方法时,是否有更好的方法来实现该功能?

4

5 回答 5

106

试试这个:

public void itemClicked(View v) {
  //code to check if this checkbox is checked!
  CheckBox checkBox = (CheckBox)v;
  if(checkBox.isChecked()){

  }
}
于 2013-08-20T13:22:52.187 回答
7

这可以解决问题:

  public void itemClicked(View v) {
    if (((CheckBox) v).isChecked()) {
        Toast.makeText(MyAndroidAppActivity.this,
           "Checked", Toast.LENGTH_LONG).show();
    }
  }
于 2013-08-20T13:24:27.643 回答
7
<CheckBox
      android:id="@+id/checkBox1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Fees Paid Rs100:"
      android:textColor="#276ca4"
      android:checked="false"
      android:onClick="checkbox_clicked" />

从这里开始的主要活动

   public class RegistA extends Activity {
CheckBox fee_checkbox;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_regist);
 fee_checkbox = (CheckBox)findViewById(R.id.checkBox1);// Fee Payment Check box
}

复选框被点击

     public void checkbox_clicked(View v)
     {

         if(fee_checkbox.isChecked())
         {
            // true,do the task 

         }
         else
         {

         }

     }
于 2016-12-09T11:10:03.600 回答
5

你可以试试这段代码:

public void itemClicked(View v) {
 //code to check if this checkbox is checked!
 if(((CheckBox)v).isChecked()){
   // code inside if
 }
}
于 2015-07-16T07:43:51.547 回答
0
@BindView(R.id.checkbox_id) // if you are using Butterknife
CheckBox yourCheckBox;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity); 
    yourCheckBox = (CheckBox)findViewById(R.id.checkbox_id);// If your are not using Butterknife (the traditional way)

    yourCheckBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            yourObject.setYourProperty(yourCheckBox.isChecked()); //yourCheckBox.isChecked() is the method to know if the checkBox is checked
            Log.d(TAG, "onClick: yourCheckBox = " + yourObject.getYourProperty() );
        }
    });
}

显然,您必须使用复选框的 id 来制作 XML:

<CheckBox
    android:id="@+id/checkbox_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your label"
    />

因此,知道复选框是否被选中的方法是:如果复选框被选中,(CheckBox) yourCheckBox.isChecked()则返回true

于 2018-07-03T12:06:02.293 回答