【问题标题】:How do you make a cast in a databinding expression?如何在数据绑定表达式中进行强制转换?
【发布时间】:2022-01-20 21:15:38
【问题描述】:

我有一个通过 StateFlow 发送的密封类。如何转换它以检索封闭的值? 我找不到任何数据绑定表达式的语法示例。

dataclass UserInfo(val name: String)

sealed class ResultOf<out T> {
  data class Success<out R>(val content: R): ResultOf<R>()
  data class Failure(val throwable: Throwable): ResultOf<Nothing>()
}

val model = ResultOf.Success.content(UserInfo("John Doe"))

<variable
            name = "viewModel"
            type="com.example.hello.user.ResultOf"/>

<TextView
    android:id="@+id/name"
    android:text="@{ ??? }"
/>
viewModel.Success.content.name

(UserInfo)viewModel.content.name

(viewModel as UserInfo).content.name

以上都不行

【问题讨论】:

    标签: android kotlin android-layout android-databinding


    【解决方案1】:

    目前不确定是否有办法在XML 的条件语句中使用强制转换来解决这个问题。

    您可以通过创建BindingAdapter 来解决此问题。像这样:

    data class User(val name: String)
    
    sealed class ResultOf<out T: Any> {
        data class Success<out R: Any>(val content: R): ResultOf<R>()
        data class Failure(val throwable: Throwable): ResultOf<Nothing>()
    }
    

    BindingAdapter

    @BindingAdapter("app:userName")
    fun TextView.setUserName(result: ResultOf<User>) {
        text = when(result) {
            is ResultOf.Success -> result.content.name
            is ResultOf.Failure -> ""
        }
    }
    

    布局文件:

    <data>
        <import type="com.example.hello.user.ResultOf" />
        <import type="com.example.hello.user.User" />
    
        <variable
            name="userResult"
            type="ResultOf&lt;User>" />
    </data>
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:userName="@{userResult}"/>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多