In the build. Gradle

Open the dataBinding

    buildFeatures {
        dataBinding true
    }
Copy the code

Define color values

In the colors.xml file

    <! -- Text main color -->
    <color name="app_textTheme">@color/white</color>
    <! Select color for text -->
    <color name="app_textNormal">#FF1D2835</color>
    <! -- Item background color -->
    <color name="app_BackgroundColor">#FF1C1C28</color>
    <! Control select default color -->
    <color name="app_colorAccent">#FF1D2835</color>    
Copy the code

The drawable folder defines the selected and unselected text of two files: TextView_selector_textcolor The selected and unselected background: TextView_selector_backgroundcolor


      
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/app_textTheme" android:state_selected="true" />
    <item android:color="@color/app_textNormal" android:state_selected="false" />
</selector>
Copy the code

      
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/app_colorAccent" android:state_selected="true" />
    <item android:drawable="@color/app_BackgroundColor" android:state_selected="false" />
</selector>
Copy the code

Set the BindingAdapter

/** Set the selected state of [v] to [selected] */
@BindingAdapter("android:bind_selected")
fun setViewSelected(v: View, selected: Boolean?). {
    if (v.isSelected == selected) {
        return
    }
    v.isSelected = selected.condition
}
Copy the code

xml

  <data>
        <variable
            name="item"
            type="xxx.xxx.PostType" />
        <variable
            name="viewModel"
           type="xxx.xxx.ViewModel" />
    </data>

  <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:bind_selected="@{viewModel.currentPostTypeId == item.id}"
        android:textSize="16sp"
        android:textColor="@drawable/textview_selector_textcolor"
        android:background="@drawable/textview_selector_backgroundcolor"/>
Copy the code

ViewModel

 /** Current postTypeId */
    val currentPostTypeId : ObservableInt = ObservableInt(0)
// Click the event to call down
Copy the code

Method of use

 currentPostTypeId.set(item.id!!)
Copy the code

The above is only the core code because I am used with recyclerView, ADAPTER code I will not paste, is the viewModel and item(entity class data) can be passed in, very simple, if the small white really do not understand the comment comment! Keywords: DataBinding bidirectional binding

rendering