首页 > 解决方案 > Android Checkbox setOnCheckedChangeListener 不起作用

问题描述

这应该是非常简单的事情,但由于某种原因,复选框的侦听器不起作用。

这是我的布局:

                <RelativeLayout
                android:layout_width="match_parent"
                android:layout_marginRight="16dp"
                android:layout_marginLeft="16dp"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="12sp"
                    android:layout_marginLeft="@dimen/dimen_5"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true"
                    android:layout_centerVertical="true"
                    android:textStyle="bold"
                    android:text="@string/my_text"
                    />

                <CheckBox
                    android:id="@+id/check_status"
                    android:layout_width="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentEnd="true"
                    android:layout_height="wrap_content" />
            </RelativeLayout>

这是我的片段中的实现:

CheckBox checkBox = mView.findViewById(R.id.check_status);
            checkBox.setOnCheckedChangeListener(new 
CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean 
isChecked) {
                    LOGD(TAG, "IsButton checked ? "+ isChecked);
                    Toast.makeText(getActivity(), "Check", 
Toast.LENGTH_SHORT).show();
                }
            });

就像我说的那样,这应该是非常直接的,但是听者……嗯,它什么也不听。我正在测试 Nexus 5x Oreo 和一个小的摩托罗拉棉花糖。

在某些时候,我什至尝试了 setOnClickListener() 方法:

checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LOGD(TAG, "IsButton checked ? "+ ((CheckBox) 
v).isChecked());
                }
            });

结果是一样的,我在logcat中看不到任何东西

有没有人知道为什么 Checkbox 的侦听器不能正常工作?

标签: androidevent-listenerandroid-checkbox

解决方案


如果您使用DataBinding,请设置属性,然后通过likeandroid:checked="@={viewModel.someState}"调用此侦听器ViewBinding

binding.checkBox.setOnCheckedChangeListener { _, _ ->
    //
}

setOnCheckedChangeListener不会被调用。

  1. 您可以设置app:checkListener和使用BindingAdapter

    @BindingAdapter("app:checkListener")
    fun CheckBox.setCheckedChangeListener(listener: CompoundButton.OnCheckedChangeListener) {
        setOnCheckedChangeListener(listener)
    }
    
  2. 或观察变化someState

    viewModel.someState.observe(viewLifecycleOwner) {
        viewModel.changeCheckBox()
        // Other actions.
    }
    

推荐阅读