【问题标题】:custom attribute setter error when data binding - Android数据绑定时的自定义属性设置器错误 - Android
【发布时间】:2020-07-14 11:53:37
【问题描述】:

我有自定义属性,它被声明为字符串类型,当像这样 app:cpb_title="sometsring" 将值作为 xml 中的字符串传递时,它可以工作,但是当我尝试像这样 app:cpb_title"@{model.someStringField}" 这样的数据绑定时,它给了我错误 “找不到接受参数类型 java.lang.String 的“app:cpb_title”的设置器”

我该如何解决?

attrs.xml

  <declare-styleable name="CircularProgressBar">
    <attr name="cpb_hasShadow" format="boolean"/>
    <attr name="cpb_progressColor" format="string"/>
    <attr name="cpb_backgroundColor" format="string"/>
    <attr name="cpb_title" format="string"/>
    <attr name="cpb_titleColor" format="string"/>
    <attr name="cpb_subtitle" format="string"/>
    <attr name="cpb_subtitleColor" format="string"/>
    <attr name="cpb_strokeWidth" format="integer"/>
</declare-styleable>

内部视图类

 String t = a.getString(R.styleable.CircularProgressBar_cpb_title);
    if(t!=null)
        mTitle = t;

【问题讨论】:

    标签: android data-binding android-custom-attributes


    【解决方案1】:

    您可以使用BindingAdapter 而不是在attrs.xml 文件中声明属性。请执行以下操作:

    class BindingUtil {
    
        @BindingAdapter("cpb_title")
        public static void setTitle(TextView view, String title) {
            view.setText(title);
        }
    }
    

    然后,您可以在 XML 中使用app:cpb_title 属性,如下所示:

                   <Textview
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:cpb_title="@{model.someStringField}" />
    

    【讨论】:

    • 感谢您的回答,我可以把这个 @BindingAdapter("cpb_title") 放在哪里?在模型类里面?或在自定义视图类中
    • 您可以安排任何课程。放入模型类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2016-03-05
    • 2017-06-29
    • 2017-12-07
    • 2019-10-26
    相关资源
    最近更新 更多