android - 如何在 Android Studio 中设置数据绑定(bind)的默认值?

标签 android android-livedata

我在触发代码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&lt;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&lt;EPlayState>" 
   default="EPlayState.STOPPED"
/>

最佳答案

赋值时添加空检查

playState != null ? .. : ..

但也要重新考虑为什么要在那里使用实时数据..
您也可以只绑定(bind)状态并将其设置在观察者中。

关于android - 如何在 Android Studio 中设置数据绑定(bind)的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64818041/

相关文章:

android - 大多数二维码扫描器无法扫描 Android zxing 库生成的二维码

android - 使用 LiveData 的波纹效果/点击动画

androidTest 中的 Android LiveData 返回 null

android - 如何在订阅 liveData 后仅针对新更新观察 liveData

java - 使用导航组件多次触发 LiveData 观察者

java - 单击textview时编辑SQLite数据

android - Android 抽屉导航中的共享按钮

android - 当我们点击android中 ListView 中的另一个项目时,如何取消选择所选项目

android - 没有 Room 的 NetworkBoundResource 帮助程序类

android - 如何将字节从 Swift (iOS) 传递到 Kotlin 通用模块?