簡體   English   中英

具有數據綁定的自定義視圖 -> 找不到設置器

[英]Custom View with data binding -> Cannot find setter

我需要為所有屏幕上的工具欄自定義布局,因此我創建了一個擴展 AppBarLayout 的自定義視圖 class。 它的 xml 包含一個帶有工具欄的 LinearLayout 和一個 TextView。然后我創建了一個自定義屬性來設置工具欄的標題 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"/>

我想要的和不起作用的是通過這樣的綁定設置標題

    <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 class

@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)
    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM