DataBinding: How to get resource by dynamic id?

You can use:

android:text='@{(id > 0) ? context.getString(id) : ""}'

Another solution is to create a custom @BindingAdapter for it.

@BindingAdapter({"format", "argId"})
public static void setFormattedText(TextView textView, String format, int argId){
    if(argId == 0) return;
    textView.setText(String.format(format, textView.getResources().getString(argId)));
}

And then just provide the variables separately.

<TextView
    app:format="@{@string/myFormatString}"
    app:argId="@{myPojo.resourceId}"

You could use an array if you need multiple arguments, but in my case, one was sufficient.


As of June 2016 this is possible in XML:

android:text= "@{String.format(@string/my_format_string, myPojo.resourceId)}"