[英]Android binding of drawable?
嗨,我正在嘗試使用數據綁定通過代碼將可繪制的 res 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找到
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.