Dmitry Zaitsev Dmitry Zaitsev - 1 year ago 59
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:


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:


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
, but it did not worked (which is actually expected, but I tried anyway) -
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 Source

I ended up creating my own method:

public class BindingUtils {

    public static String string(int resourceId) {
        return MyApplication


Declaring an import for it:


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



And just calling it during binding:


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