数据绑定时自定义属性设置器错误 - Android

3
我有一个自定义属性,声明为字符串类型。当我在XML中以纯字符串形式传递值时(如 app:cpb_title="sometsring"),它可以正常工作,但是当我尝试使用数据绑定(如 app:cpb_title"@{model.someStringField}")时,会出现错误"cannot find setter for "app:cpb_title" that accepts parameter type java.lang.String"

我该如何解决这个问题?

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;
1个回答

2
您可以使用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") 放在哪里?是放在模型类中还是自定义视图类中? - Giorgi Abashidze
你可以将任何类放在模型类中。 - Shalu T D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接