Android 可绘制对象的绑定?

Android binding of drawable?

您好,我正在尝试使用数据绑定通过代码将可绘制资源 ID 绑定到文本视图中,但我一直收到此错误:

Cannot find a getter for <android.widget.TextView android:background> that accepts parameter type 'int'

If a binding adapter provides the getter, check that the adapter is annotated correctly and that the parameter type matches.

这是viewModel代码

   @DrawableRes
    private var buttonBg: Int = R.drawable.white_btn

    @Bindable
    fun getButtonBg(): Int {
        return buttonBg
    }

    @Bindable
    fun setButtonBg(bgRes: Int) {
        if (buttonBg != bgRes) {
            buttonBg = bgRes
            notifyPropertyChanged(BR.buttonBg)
        }
    }

xml

 <TextView
            android:id="@+id/toggle_textButton"
            style="@style/TextAppearance.AppCompat.Body1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@={viewModel.buttonBg}"
            android:padding="5dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="@string/follow" />

抱歉,我对 Kotlin 不太熟悉,但我知道 Java 您可以设置静态数据绑定以确保它将使用资源:

    @BindingAdapter("android:background")
    public static void setBackground(TextView view, Integer buttonBackground){
        Drawable background = view.getContext().getResources().getDrawable(buttonBackground, null);
        view.setBackground(background);
    }

然后您可以保留布局中的绑定 xml。

编辑: 可以在 https://developer.android.com/topic/libraries/data-binding/binding-adapters.html#kotlin

找到更多信息