如何将MutableLiveData <Boolean>绑定到复选框

问题描述

问题在于,即使我取消选中复选框,当我单击按钮时,Toast消息也始终显示checked为真

class MainActivity : AppCompatActivity() {

    private lateinit var binding: MainActivityLayoutBinding

    var checked = MutableLiveData<Boolean>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        checked.value = true

        binding = DataBindingUtil.setContentView(this,R.layout.main_activity_layout)
        binding.checked = checked.value

        binding.lifecycleOwner = this
        binding.showValue.setOnClickListener{

            Toast.makeText(this,checked.value.toString(),Toast.LENGTH_SHORT).show()

        }
    }
}

Xml代码

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>
        <variable
            name="checked"
            type="Boolean" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Check"
            android:id="@+id/checkBox"
            android:checked="@={checked}"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Salva"
            android:id="@+id/showValue"/>

    </LinearLayout>
</layout>

解决方法

这是因为您设置了checked.value = true 尝试删除此行

,

删除此行

binding.checked = checked.value

观察live-data的变化,然后更新绑定视图

checked .observe(this,Observer { 
             binding.checked = it
        })

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...