androidandroid-databindingandroid-attributesandroid-binding-adapter

Set via Data-Binding API a well known attribute value


I have an custom attribute from a custom view defined line this:

<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 detects this and offers me a autocompletion, which is great. So the xml attribute will look like app:order="byValue". However since I want to use a BindingAdapter from the data binding API, I need to use it with an @ sign like this: app:order="@{byValue}", unfortunately this does not compile.

Then I tried to use a constant which I use internally too like this: app:order="@{com.example.views.ExampleView.ORDER_BY_VALUE}", but this does not compile too. I can just use app:order="@{0}", sure this works because it is defined like that, however it is not intuitive why I am using 0 there.

Any idea how can I write a more readable code to solve this issue?


Solution

  • It is necessary to create code for the enum values:

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

    Import the class / object holding these enums to your XML:

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

    Then you can reference them:

    app:order="@{Order.INSTANCE.BY_KEY}"