具有数据绑定的自定义视图 -> 找不到资源库



我需要在所有屏幕上为工具栏创建一个自定义布局,所以我创建了一个扩展AppBarLayout的自定义视图类。它的xml包含一个带有Toolbar和TextView的LinearLayout。然后,我创建了一个自定义属性,用xml设置工具栏的标题。看起来像这个

class MyAppBarLayoutCustomView (...) : AppBarLayout(...) {
init {
val typedArray = context.obtainStyledAttribute(attrs, R.stylable.myAppBarLayoutCustomView, defStyle, 0)
binding.myToolBar.title = typedArray.getString(R.stylable.myAppBarLayoutCustomView_customToolbarTitle) ?: ""
typedArray.recylce()
}
}

如果我只是在这样的片段或活动中通过xml设置标题,这很好

<MyAppBarLayoutCustomView
android:id="@+id/my_app_bar_layout_view"
andorid:layout_width="match_parent"
andorid:layout_height="wrap_content"
app:customToolbarTitle="@string/mainscreen_title"/>

我想要的和NOT的工作是通过这样的绑定设置标题

<data>
<variable
name="viewModel"
type="com.my.cool.app.MainScreenViewModel/>
</data>
<LinearLayout ...>
<MyAppBarLayoutCustomView
android:id="@+id/my_app_bar_layout_view"
andorid:layout_width="match_parent"
andorid:layout_height="wrap_content"
app:customToolbarTitle="@{viewModel.title}"/>
</LinearLayout>
</layout>

viewModel中的绑定如下

private val _title = NonNullMutableLiveData(R.string.default_title)
val title: NonNullLiveData<Int> = _title
...
_title.postValue(R.string.custom_title)

我得到的错误如下

Cannot find a setter for <MyAppBarLayoutCustomView app:customToolbarTitle> that accepts parameter type 'com...livedata.NonNullLiveData<java.lang.Integer>
If a binding adapter provides the setter, check that the adapter is annotated correctly and that the parameter type matches.

您必须在自定义视图类中使用BindingAdapter

@BindingAdapter("app:customToolbarTitle")
fun setCustomToolbarTitle(view: MyAppBarLayoutCustomView, text: Int) {
// call the method in customview which sets the string value for title view
view.methodnameForsettingTitle(text)

}

最新更新