rekire
rekire

Reputation: 47945

How to define a custom BindingMethod for a TextView?

I am starting to work with the new data binding API. I want to bind on a TextView a custom property where I change the text and background at once. As far I understood the api there is a @BindingMethod annotation for this, but the documentation is there a little weak.

I want something like this:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="Important"
    tools:background="@drawable/bg_badge_important"
    tools:textColor="#fff"
    android:id="@+id/badge"
    custom:badge="@{item.badge}"/>

Where this item.badge is a string like important or notice. For i18n I cannot use this string directly but this will help me to choose the right text and the right background image.

Can you give me a small example or a reference how to use this attribute? I just found one answer on Stack Overflow, but this does not answer my question.

Upvotes: 1

Views: 1961

Answers (1)

yigit
yigit

Reputation: 38243

Just create a public static method on your codebase and annotate with @BindingAdapter.

Here is an example for fonts:

https://plus.google.com/+LisaWrayZeitouni/posts/LTr5tX5M9mb

Edit by rekire I ended in using this code:

@BindingAdapter({"bind:badge"})
public static void setBadge(TextView textView, String value) {
    switch(value) {
        case "email":
            textView.setText(R.string.badge_email);
            textView.setBackgroundResource(R.drawable.bg_badge_email);
            break;
        // other cases
    }
}

Upvotes: 2

Related Questions