Get formatted resource string from xml layout

How to get formatted string from res\values\strings.xmlin xml layout file? For example: To have res\values\strings.xmlas follows:

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

and xml format file as follows:

<?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 a resource string review_web_urlpassing / formatted with the value @ {model.anchorHtml}?

There is a way to get this formatted string, as in java code:

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

but from xml layout?

+4
source share
1 answer

You can use the BindingAdapter!

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

You will need to do 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));
}

xml - :

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

BindingAdapter ! , , Utils.

+3

Source: https://habr.com/ru/post/1694181/


All Articles