我在触发代码A之前为变量playState
赋值,但是代码A仍然得到如下错误信息。
方法kotlin.jvm.internal.Intrinsics.checkNotNullParameter,参数aEPlayState
我认为playState
是一个LiveData
,初始值为null,可能会在我赋值给它之前出错。
我该如何解决?代码 B 对吗?
代码A
<?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">
<data>
<import type="android.view.View" />
<import type="androidx.lifecycle.LiveData" />
<import type="info.dodata.voicerecorder.model.EPlayState" />
<variable
name="playState"
type="LiveData<EPlayState>" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageButton
android:id="@+id/btnPlay"
android:layout_width="@dimen/round_button_small"
android:layout_height="@dimen/round_button_small"
app:srcCompat="@drawable/play_play"
app:iamgeForPlayPause="@{playState}"
/>
</LinearLayout>
</layout>
@BindingAdapter("app:iamgeForPlayPause")
fun imageForPlayPause(aImageButton: ImageButton, aEPlayState: EPlayState) {
...
}
enum class EPlayState {
STOPPED,
PLAYING,
PAUSED
}
代码B
<variable
name="playState"
type="LiveData<EPlayState>"
default="EPlayState.STOPPED"
/>
最佳答案
赋值时添加空检查
playState != null ? .. : ..
但也要重新考虑为什么要在那里使用实时数据..
您也可以只绑定(bind)状态并将其设置在观察者中。
关于android - 如何在 Android Studio 中设置数据绑定(bind)的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64818041/