Android 中的格式化字符串在 ViewModel/LiveData 的首次更新之前未正确显示

Formatted strings in Android aren't displayed correctly before first update from ViewModel/LiveData

我像往常一样在 /res/values/strings.xml 中定义了一些字符串,并且我正在尝试格式化和 HTML 样式。如前所述here and here,它们都是这样定义的

<string name="my_string">&lt;b>stuff in bold&lt;/b> %1$s</string>

为了在屏幕上显示它们,我必须这样做:

myTextView.text = Html.fromHtml(getString(R.string.my_string, "first argument"), FROM_HTML_MODE_LEGACY)

最后我应该能够在屏幕上看到“粗体显示的东西第一个参数”,但是这个参数实际上是由 ViewModel 提供的,只要它的 LiveData 发生变化,所以在我的片段我有以下代码:

myViewModel.myLiveData.observe(viewLifecycleOwner) {
    myTextView.text = Html.fromHtml(getString(R.string.my_string, it), FROM_HTML_MODE_LEGACY)
}

但是,当我启动应用程序时,字符串会像这样逐字显示

<b>stuff in bold</b> %1$s

直到观察到并应用 LiveData 的第一次更改。到目前为止,我已经通过立即向所有 LiveData 字段发送 "" 来解决问题,就好像它们需要在显示之前进行初始化一样;结果是“stuff in bold”,这是我在 LiveData 收到有意义的更新之前想要的。这是唯一的方法还是我遗漏了什么?

创建 1 个单独的方法。

fun getFormattedString(myString : String) :  String{
  return Html.fromHtml(getString(R.string.my_string, myString), FROM_HTML_MODE_LEGACY)
}

从片段的 activityonViewCreated 的 onCreate 调用此方法。

这是为了设置stuff in bold

myTextView.text = getFormattedString(" ")

同样,也这样做。这是来自 livedata 的实际字符串数据。

myViewModel.myLiveData.observe(viewLifecycleOwner) {
    myTextView.text = getFormattedString(it)
}

原因是:当我们使用格式化字符串时,我们必须使用Html.fromHtml()来获取实际的格式化字符串。布局 XML 无法从 string.xml.

获取此格式化字符串