5

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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.