android - 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 的侦听器不能正常工作?
解决方案
如果您使用DataBinding
,请设置属性,然后通过likeandroid:checked="@={viewModel.someState}"
调用此侦听器ViewBinding
binding.checkBox.setOnCheckedChangeListener { _, _ ->
//
}
setOnCheckedChangeListener
不会被调用。
您可以设置
app:checkListener
和使用BindingAdapter
:@BindingAdapter("app:checkListener") fun CheckBox.setCheckedChangeListener(listener: CompoundButton.OnCheckedChangeListener) { setOnCheckedChangeListener(listener) }
或观察变化
someState
:viewModel.someState.observe(viewLifecycleOwner) { viewModel.changeCheckBox() // Other actions. }
推荐阅读
- python - GCP Dataflow 管道在 DirectRunner 中的运行速度比 DataflowRunner 快
- node.js - fs-extra readFile 不是函数
- java - 增强的 For 循环查询
- r - 以点 (.) 和下划线 (_) 开头的对象创建 R
- json - 如何在python3中从具有多个值的json键中提取一个signle值?
- reactjs - 使用 ReactJS 上传文件
- maven - 无法在 Elasticsearch 5.6.16 上初始化类 org.elasticsearch.painless.WriterConstants 并且依赖于 jayway
- php - 操作 WooCommerce 类别描述输出
- azure - Azure 云服务:RoleEnvironment.StatusCheck 事件未触发
- ios - 检测轮播中可见的图像或结构