I know that it is possible to reference resources in layout by their resource id:
android:text=\"@{@string/resourceName}\"
However, I would
Another solution if you already have Context
defined in your xml then you will not need to import String
class.
android:text="@{@string/myFormatString(context.getString(pojo.res))}"
will work for
<string name="myFormatString">Value is: %s</string>
If you don't have context in your xml. then follow this
<data>
<variable
name="context"
type="abc.UserActivity"/>
<variable
name="pojo"
type="abc.MyPOJO"/>
</data>
and in your Activity
ActivityUserBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_user);
binding.setPojo(new MyPOJO());
binding.setContext(this);
Kotlin version:
@BindingAdapter("template", "resId")
fun TextView.setFormattedText(template: String, resId: Int) {
if (template.isEmpty() || resId == 0) return
text = template.format(resources.getString(resId))
}
in xml
<TextView
app:template="@{@string/myFormatString}"
app:resId="@{viewModel.resourceId}"/>
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.
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) : ""}'
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.