vit*_*nio 4 string resources android formatted-text
如何从res\values\strings.xmlxml布局文件中获取格式化的字符串?例如:有一个res\values\strings.xml这样的:
<resources>
<string name="review_web_url"><a href="%1$s">Read online</a></string>
</resources>
Run Code Online (Sandbox Code Playgroud)
和这样的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>
Run Code Online (Sandbox Code Playgroud)
如何获得review_web_url使用值@ {model.anchorHtml}传递/格式化的资源字符串?
有一种方法可以像我在Java代码中那样获得此格式化的字符串:
String anchorString = activity.getString(R.string.review_web_url, model.getAnchorHtml());
Run Code Online (Sandbox Code Playgroud)
但是从xml布局?
您可以使用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));
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的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>
Run Code Online (Sandbox Code Playgroud)
BindingAdapter将为您完成艰苦的工作!请注意,您需要将其设为静态和公共,因此可以将其放在Utils类中。
| 归档时间: |
|
| 查看次数: |
1467 次 |
| 最近记录: |