可能是这个重复的问题,但我找不到答案。
我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();
}
});
答案 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"/>