【问题标题】:Font tag inside string tag is not read with Data Binding Android使用数据绑定 Android 无法读取字符串标签内的字体标签
【发布时间】:2021-04-26 19:00:03
【问题描述】:

字符串资源:

<string name="hint_dob_mandatory">Date of birth<font color='#FFFF0000'>  *</font></string>
                  <!-- Already tried with '#FFFF0000', "#FFFF0000" -->
<string name="hint_dob">Date of birth</string>

以下代码运行良好:

android:hint="@string/hint_dob_mandatory"

以下是正确的实际输出:(正常使用字符串 res)

这里,数据绑定问题:

 android:hint="@{ANY_TRUE_CONDITION ? @string/hint_dob_mandatory : @string/hint_dob}

以下是有问题的实际输出:(使用字符串 res 的数据绑定)

【问题讨论】:

    标签: android android-layout data-binding


    【解决方案1】:

    关键是看方法的签名。 如果你没有使用数据绑定,你实际上是在使用这个方法:

    fun EditText.setHint(resourceId: Int)
    

    使用Databinding时,@string/hint_dob_mandatory会自动解析为String,其实你就是用这个方法:

    fun EditText.setHint(hint: CharSequence)
    

    第一个很好地处理字体标签,但第二个将忽略它。基本上,Databinding 试图变得聪明,但这样做使用了错误的方法。

    现在,要解决它,您有 2 个选择:

    1) 为提示显式设置 ResourceId

    <data>
        <variable
            name="hintResource"
            type="Integer" />
    </data>
    
    <EditText
        android:hint="@{hintResource}" />
    

    使用这种方法,您需要在绑定上设置hintResource

    binding.hintResource = R.string.hint
    

    这有效地确保setHint(res: Int) 变体正在被使用

    2) 导入您的 R 文件

    <data>
        <import type="com.your.package.R" />
    </data>
    
    <EditText
        app:resourceHint="@{ANY_TRUE_CONDITION ? R.string.hint_dob_mandatory : R.string.hint_dob}
    

    通过导入R 文件,您可以在dataBinding 表达式中使用它。通过使用 R.string.hint 您表明您使用资源。而@string/hint 实际上会将该资源转换为字符串。

    最后,也可以将两者结合起来,以及创建自定义的 BindingAdapter。但最后都是一样的,只要你确保使用@StringRes Int而不是String

    【讨论】:

    • 感谢您的详细回答,我正在使用上述选项中的第二个。
    猜你喜欢
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多