5

我有一个来自自定义视图定义行的自定义属性:

<declare-styleable name="ExampleView">
    <attr name="order">
        <enum name="byValue" value="0" />
        <enum name="byKey" value="1" />
    </attr>
    <!-- and some more attributes -->
</declare-styleable>

Android Studio 检测到这一点并为我提供了一个自动完成功能,这很棒。所以 xml 属性看起来像app:order="byValue". 但是,由于我想使用BindingAdapter数据绑定 API 中的 a ,因此我需要将它与这样的@符号一起使用:app:order="@{byValue}",不幸的是这无法编译。

然后我尝试使用一个我在内部使用的常量,就像这样:app:order="@{com.example.views.ExampleView.ORDER_BY_VALUE}",但这也不能编译。我可以使用app:order="@{0}", 确定这行得通,因为它是这样定义的,但是我在0那里使用它并不直观。

知道如何编写更具可读性的代码来解决此问题吗?

4

1 回答 1

1

有必要为枚举值创建代码:

object Order {
    const val BY_VALUE = 0
    const val BY_KEY = 1
}

将包含这些枚举的类/对象导入您的 XML:

<import type="com.example.Order" />

然后你可以参考它们:

app:order="@{Order.INSTANCE.BY_KEY}"
于 2020-12-10T13:05:04.243 回答