【问题标题】:onCheckedChanged not called on AppCompatCheckBox view未在 AppCompatCheckBox 视图上调用 onCheckedChanged
【发布时间】:2018-03-07 12:13:13
【问题描述】:

我在代码中动态创建了一些自定义复选框视图。这些复选框继承自 AppCompatCheckBox。

public class ChangeableSelectionParameterValueCheckbox extends android.support.v7.widget.AppCompatCheckBox

我在代码中添加了 OnCheckChangedListener。 添加的 OnCheckedChangeListener 是 android.widget.CompoundButton.OnCheckedChangeListener;

changeableSelectionParameterValueCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //on checked changed code here
            }
        });

问题:永远不会调用 onCheckedChanged。 自定义复选框似乎不可点击。

当我将自定义视图类更改为从 android.widget.CheckBox 继承时,一切正常。

有什么建议吗?

【问题讨论】:

  • CheckBox 可以做同样的任务,为什么还需要 AppCompatCheckBox
  • 我真的不需要它,但 Android Studio 给了我一条错误 lint 消息,说“这个自定义视图应该扩展 android.support.v7.widget.AppCompatCheckbox”。而且因为我没有立即看到此 AppCompatCheckbox 类中 onCheckedChange 代码的任何特定更改,所以我想知道为什么这在此类中不再起作用。
  • 如果我将类更改为继承自 AppCompatCheckbox 而不是 Checkbox(如 android studio 建议的那样),我希望我的应用程序行为保持不变。但事实并非如此。这就是我问这个问题的原因,但显然值得一票否决!

标签: android android-appcompat android-checkbox oncheckedchanged


【解决方案1】:

我遇到了同样的问题,并通过将属性“可点击”设置为 true 来解决它。 它适用于代码和 XML,因此请选择以下解决方案之一:

AppCompatCheckbox check;
check.setClickable(true);
<android.support.v7.widget.AppCompatCheckBox xmlns:android="http://schemas.android.com/apk/res/android"
                                             android:id="@+id/id_checkbox"
                                             android:layout_width="match_parent"
                                             android:layout_height="wrap_content"
                                             android:clickable="true"
                                             android:gravity="center_vertical"/>

【讨论】:

    猜你喜欢
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 2012-10-27
    • 2014-01-13
    • 1970-01-01
    相关资源
    最近更新 更多