簡體   English   中英

如何使用 **style** 屬性從數據綁定設置樣式資源

[英]How to set style resource from data binding using **style** attribute

在 viewModel 中,我有一個 function,如下所示:

fun getTextInputStyle(): Int {
val style = if (isTrue) {
    R.style.styleOne
} else {
    R.style.styleTwo
}
return style

}

在 XML 文件中有一個 textInputLayout 從 ViewModel 調用 function:

<com.google.android.material.textfield.TextInputLayout
android:id="@+id/til_first_name"
style="@{viewModel.getTextInputStyle}"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginTop="@dimen/_13sdp"
android:layout_marginEnd="@dimen/_16sdp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/rg_title">


</com.google.android.material.textfield.TextInputLayout>

這里是控制台中記錄的錯誤:

      Cannot find a setter for 
        <com.google.android.material.textfield.TextInputLayout style> 
        that 
        accepts parameter type 'int'
   If a binding adapter provides the setter, check that the adapter is 
   annotated correctly and that the parameter type matches.

您可以使用綁定適配器來設置這樣的樣式。

@BindingAdapter("bindTextViewStyle")
fun TextView.bindTextViewStyle(styleResourceId: Int) {
    this.style(styleResourceId)
}

並在 XML

<TextView
    app:bindTextViewStyle="@{viewModel.textStyle}"
    .../>

暫無
暫無

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

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