Android 双向数据绑定(bind) 三元运算符必须恒定的问题

标签 android kotlin android-room android-databinding android-viewmodel

我的EditText是这样的:

<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@={viewModel.isAddCase? ``: `` + viewModel.currentStudent.age}"    //problem here
    android:inputType="number" />

我想要EditText不显示基于 isAddCase 的任何内容(空字符串)变量,这是一个 MutableLiveData<Boolean>ViewModel 时初始化创建类对象(在 init{} block 内)。

这是我得到的错误:

The expression '((viewModelIsAddCaseGetValue) ? ("") : (javaLangStringViewModelCurrentStudentAge))' cannot be inverted, so it cannot be used in a two-way binding

Details: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@37a418c7

更新

即使这不起作用,也会显示相同的错误:

android:text="@={viewModel.currentStudent.age == 0? ``: `` + viewModel.currentStudent.age}"

我猜三元运算不能很好地用于双向 DataBinding .

最佳答案

好吧,这几天我已经找到了完美的解决方案:

<强>1。创建BindingAdapter函数:

object DataBindingUtil {                                    //place in an util (singleton) class
    @BindingAdapter("android:text", "isAddCase")            //custom layout attribute, see below
    @JvmStatic                                              //required
    fun setText(editText: EditText, text: String, isAddCase: Boolean) {     //pass in argument
        if (isAddCase) editText.setText("") else editText.setText(text)
    }
}

<强>2。在View中应用自定义属性:

<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:inputType="number"
    android:text="@={`` + viewModel.currentStudent.age}"        //two-way binding as usual
    app:isAddCase="@{viewModel.isAddCase}" />                   //here

  • 仅当使用 EditText 和自定义属性同时时才会触发 BindingAdapter 函数。

关于Android 双向数据绑定(bind) 三元运算符必须恒定的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64596538/

相关文章:

java - 一对多关系中的父实体更新不会删除 Spring Jpa Childs

android - Room flowable调用多次

android - 请在构建器中提供迁移或在构建器中调用 fallbackToDestructiveMigration,在这种情况下 Room 将重新创建所有表

android - 如何在 Kotlin 中将对象列表从 Activity A 传递到 Activity B?

android - Flutter:任务 ':app:processDebugGoogleServices' 执行失败

java - 如何在SQLite数据库的onCreate()函数中使用getWritableDatabase? (安卓)

android - 如何使用 Mockk 使用Transaction 方法模拟 android 房间

android - 非静态方法问题

generics - 针对F <out X>的特定情况F <Nothing>缺少HKT的解决方法

kotlin - Kotlin 中的运算符重载以及此代码如何工作?