Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...