从xml布局获取格式化的资源字符串

时间:2018-02-27 14:05:41

标签: android string resources formatted-text

如何在xml布局文件中从res\values\strings.xml获取格式化字符串? 例如: 像这样res\values\strings.xml

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

和像这样的xml布局文件:

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

如何使用@ {model.anchorHtml}值获取传递/格式化的资源字符串review_web_url

有一种方法可以像在java代码中那样获取这个格式化的字符串:

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

但是从xml布局?

1 个答案:

答案 0 :(得分:4)

您可以使用BindingAdapter!

看看这个链接,它将向您介绍BindingAdapters: https://developer.android.com/reference/android/databinding/BindingAdapter.html

你必须做这样的事情:

@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类中。