Android CheckBox onClickListener不起作用

时间:2015-11-17 08:24:27

标签: android checkbox

可能是这个重复的问题,但我找不到答案。

ClickListener的{​​{1}}不起作用。

这个xml:

CheckBox

来自Activity的代码:

<CheckBox
            android:id="@+id/checkbox_visibility"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/mat_card_padding"/>

UPD 我从答案添加代码 - 但这对我不起作用(

        mVisibilityCheckBox = (CheckBox) findViewById(R.id.checkbox_visibility);
        mVisibilityCheckBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // this method doesn't call
                    Toast.makeText(SettingsActivity.this, "isChecked - " + mVisibilityCheckBox.isChecked(), Toast.LENGTH_SHORT).show();
                }
            });

5 个答案:

答案 0 :(得分:6)

mVisibilityCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // perform logic
           Toast.makeText(SettingsActivity.this, "isChecked - " + mVisibilityCheckBox.isChecked(), Toast.LENGTH_SHORT).show();
        }

    }
});

答案 1 :(得分:2)

检查这个例子。这可以帮到你。 http://www.bipinrupadiya.com/2013/08/android-checkbox-setoncheckedchangelist.html

<强>编辑: 此处所需的代码如下所示:

CheckBox hin = (CheckBox) findViewById(R.id.chkHindi);
hin.setOnCheckedChangeListener( new OnCheckedChangeListener() {

   @Override
   public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(), "Check box "+arg0.getText().toString()+" is "+String.valueOf(arg1) , Toast.LENGTH_LONG).show();
   }
  } );

答案 2 :(得分:1)

添加此代码,它将起作用

mVisibilityCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (mVisibilityCheckBox.isChecked()) {
                // this doesn't work
                Toast.makeText(SettingsActivity.this, "isChecked - " + mVisibilityCheckBox.isChecked(), Toast.LENGTH_SHORT).show();
            }

        }
    });

答案 3 :(得分:0)

希望这有帮助

mVisibilityCheckBox.setOnClickListener(new OnClickListener()
 {

        @Override
        public void onClick(View v) {

            // TODO Auto-generated method stub

            if(satView.isChecked()){

                System.out.println("Checked");

            }else{

                System.out.println("Un-Checked");
            }
        }
    });

答案 4 :(得分:-2)

只需在CheckBox xml中添加clickable="true"

例如:

<CheckBox
     android:id="@+id/checkbox_visibility"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginRight="@dimen/mat_card_padding"
     android:clickable="true"/>