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?
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)}"
You can use:
android:text='@{(id > 0) ? context.getString(id) : ""}'