简体   繁体   English

如何使用 **style** 属性从数据绑定设置样式资源

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

In viewModel i had a function like this:在 viewModel 中,我有一个 function,如下所示:

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

} }

In XML file there is a textInputLayout call the function from ViewModel:在 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>

And here the error logged in the console:这里是控制台中记录的错误:

      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.

You can use binding adapter to set style like this.您可以使用绑定适配器来设置这样的样式。

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

and in XML并在 XML

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM