Jono
Jono

Reputation: 18128

Android binding of drawable?

Hi am tryin to use data binding to bind a drawable res ID into a textview via code but i keep getting this error:

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.

Here is the viewModel code

   @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" />

Upvotes: 0

Views: 1205

Answers (1)

JacquesBauer
JacquesBauer

Reputation: 266

Sorry I am not as familiar with Kotlin, but I know in Java that you can setup a static data binding to ensure it will use resources:

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

You can then keep the binding as you have it in your layout xml.

Edit: More information can be found at https://developer.android.com/topic/libraries/data-binding/binding-adapters.html#kotlin

Upvotes: 1

Related Questions