Dmitry Zaitsev Dmitry Zaitsev - 3 months ago 16
Android Question

DataBinding: How to get resource by dynamic id?

I know that it is possible to reference resources in layout by their resource id:

android:text="@{@string/resourceName}"


However, I would like to reference resource by id which is known only at runtime. As a simple example, imagine we have such model:

public class MyPOJO {

public final int resourceId = R.string.helloWorld;

}


And now I need to use this value as a value in a format string. Let's call it

<string name"myFormatString">Value is: %s</string>


The most straightforward approach does not work:

android:text="@{@string/myFormatString(myPojo.resourceId)}


This will just put integer value into placeholder (also it proves that I initialized my POJO correctly, so I'm not providing whole layout here).

I also tried using
@BindingConversion
, but it did not worked (which is actually expected, but I tried anyway) -
int
was still assigned to placeholder and binding method was not called.

How can I explicitly get resource by it's id in DataBinding library?

Answer

I ended up creating my own method:

public class BindingUtils {

    public static String string(int resourceId) {
        return MyApplication
                .getApplication()
                .getResources()
                .getString(resourceId);
    }

}

Declaring an import for it:

<data>

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

    ...

</data>

And just calling it during binding:

android:text="@{@string/myFormatString(BindingUtils.string(myPojo.resourceId))}"

Would be nice to have out-of-the-box method for that. DataBinding is sitll in Beta - so maybe it will come in future.