ObservableBoolean.get()总是给出空指针异常

时间:2019-01-06 19:47:37

标签: android data-binding kotlin android-databinding

我的ObservableBoolean总是触发空指针异常“ java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'boolean android.databinding.ObservableBoolean.get()'”

我正试图通过绑定视图调用它。视图模型如下所示:

class TempViewModel {
    val isLayoutVisible: ObservableBoolean = ObservableBoolean(false)

    fun onClicked(view: View){
        isLayoutVisible.set(!isLayoutVisible.get())
    }
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

<data>
    <import type="android.view.View"/>

    <variable
            name="tempViewModel"
            type="com.example.project.TempViewModel"/>
</data>

<android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_height="wrap_content">

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{tempViewModel::onClicked}"
            android:src="@drawable/ic_exclamation"/>

    <TextView
            android:layout_width="wrap_content"
            android:visibility="@{tempViewModel.isLayoutVisible ? View.VISIBLE : View.GONE}"
            android:layout_height="wrap_content"/>

</android.support.constraint.ConstraintLayout>
</layout>

点击侦听器进入onClicked,但随后在isLayoutVisible.get()上崩溃。有人知道为什么吗?

0 个答案:

没有答案