4

How can get a formatted string from res\values\strings.xml in xml layout file? Eg: Have a res\values\strings.xml like this:

<resources>
    <string name="review_web_url"><a href="%1$s">Read online</a></string>
</resources>

and an xml layout file like this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable name="model" type="com.example.model.MyModel" />
    </data>

    <TextView android:text="@string/review_web_url"/>
</layout>

How can I get the resource string review_web_url passing/formatted with the value @{model.anchorHtml} ?

There is a way to get this formatted string like I do in java code:

String anchorString = activity.getString(R.string.review_web_url, model.getAnchorHtml());

but from xml layout?

vitiello.antonio
  • 323
  • 3
  • 12

1 Answers1

6

You can use a BindingAdapter!

Take a look at this link, that'll introduce you to BindingAdapters: https://developer.android.com/reference/android/databinding/BindingAdapter.html

You will have to make something like this:

@BindingAdapter(values={"textToFormat", "value"})
public static void setFormattedValue(TextView view, int textToFormat, String value) 
{
    view.setText(String.format(view.getContext().getResources().getString(textToFormat), value));
}

Then, in your xml, you can do something like this:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable name="model" type="com.example.model.MyModel" />
    </data>

    <TextView 
        ...
        app:textToFormat="@string/review_web_url"
        app:value="@{model.anchorHtml}"/>
</layout>

The BindingAdapter will do the hard work for you! Note that you need to make it static and public, so you can put it inside an Utils class.

Gregorio Palamà
  • 1,965
  • 2
  • 17
  • 22