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

问题描述 投票:4回答:1

如何在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布局?

android string resources formatted-text
1个回答
3
投票

你可以使用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类中。

© www.soinside.com 2019 - 2024. All rights reserved.