【问题标题】:Android Studio 3.4 Kotlin BindingAdapter crashes the apAndroid Studio 3.4 Kotlin BindingAdapter 使应用程序崩溃
【发布时间】:2019-05-19 16:48:08
【问题描述】:

我几天来一直在尝试在 Android Studio 3.4(最后一次更新)中使用 Kotlin 中的 BindingAdapter,但似乎没有任何效果。

我首先尝试了以下教程:https://codelabs.developers.google.com/codelabs/android-databinding/#7 当我到达第 8 步时,它就会输出错误。

此外,我尝试了一个简单的示例,其中包含一个空应用程序、一个 Activity、一个 ViewModel 和一个 BindingAdapter。这是 XML 代码。

<?xml version="1.0" encoding="utf-8"?>
<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable name="viewmodel" 
                  type="com.example.testbindingadapter.DataViewModel"/>
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:greetings="@{viewmodel.name}"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" 
                android:id="@+id/textView"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

现在是带有 BindingAdapter 的 ViewModel

class DataViewModel : ViewModel() {

    private val _name = MutableLiveData<String>()
    val name : LiveData<String> = _name
    init {
        _name.value = "Amath"
    }
}

@BindingAdapter("greetings")
fun setName(view: TextView, text: String) {
    view.text = "Welcome, $text"
}

我还在 Gradle 中启用了 dataBinging。我按照以下线程Cannot find the setter for attribute in Data binding 中的建议添加了apply plugin: 'kotlin-kapt'。一开始我有一个错误msg:Cannot find the setter for attribute databinding,后来错误消失了,但应用程序就崩溃了。

你能帮忙吗?

【问题讨论】:

  • 你设置了 binding.viewmodel = viewModel 吗?

标签: android android-studio kotlin kotlin-android-extensions


【解决方案1】:

您永远不会将视图模型设置为数据绑定:

binding.viewmodel = viewModel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2017-10-27
    相关资源
    最近更新 更多