简体   繁体   English

如何通过数据绑定传递一个密封的 class

[英]How to pass a sealed class through data binding

I have the following sealed class:我有以下密封的 class:

sealed class Pot(
    val ball: Ball,
    val potType: PotType,
    val potAction: PotAction
) {
    class HIT(hitBall: Ball) : Pot(hitBall, PotType.HIT, PotAction.CONTINUE)
    object SAFE : Pot(Ball.NOBALL, PotType.SAFE, PotAction.SWITCH)
    object MISS : Pot(Ball.NOBALL, PotType.MISS, PotAction.SWITCH)
    class FOUL(foulBall: Ball, foulAction: PotAction): Pot(foulBall, PotType.FOUL, foulAction)
    class REMOVERED(removeBall: Ball): Pot(removeBall, PotType.REMOVERED, PotAction.CONTINUE)
    object ADDRED: Pot(Ball.RED, PotType.ADDRED, PotAction.CONTINUE)
}

I want to pass this from the xml to the view model as such:我想将它从 xml 传递到视图 model ,如下所示:

<data>
    <import type="com.example.snookerscore.fragments.game.Pot"/>
    // other variables
</data>

Then I use lambdas in the views I need to pass the information to the click handler:然后我在需要将信息传递给点击处理程序的视图中使用 lambda:

<TextView
    android:id="@+id/game_btn_act_safe"
    style="@style/temp_btn"
    android:onClick="@{() -> gameViewModel.updateFrame(Pot.SAFE)}"
    // Other view Properties 
/>

I get this error:我收到此错误:

Could not find identifier 'Pot'.找不到标识符“Pot”。 Check that the identifier is spelled correctly, and that no or tags are missing.检查标识符是否拼写正确,以及是否缺少标签。

I've also tried importing Pot.SAFE directly, but it still doesn't work我也试过直接导入Pot.SAFE还是不行

Data binding uses Java to generate codes and in your XMLs you have to code in Java (eg ternary conditions are written with condition? A: B instead of Kotlin if/else )数据绑定使用 Java 来生成代码,并且在您的 XML 中您必须在 Java 中编写代码(例如,三元条件是用condition? A: B而不是 Z539A3A5859D24FB7B129E74D61F09 if/else

So you have to access those object using Java syntax, something like:因此,您必须使用 Java 语法访问那些 object,例如:

android:onClick="@{v -> gameViewModel.updateFrame(Pot.SAFE.INSTANCE)}"

used;用过的;

<variable
            name = "sealedName"
            type="com.example.snookerscore.fragments.game.Pot"/>

Removed已移除

<import type="com.example.snookerscore.fragments.game.Pot"/>

final;最后;

android:onClick="@{() -> gameViewModel.updateFrame(sealedName.SAFE)}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM