利用DataBinding优雅的实现,文本选中切换字体背景的颜色效果

1,303 阅读1分钟

在build.gradle里面

开启dataBinding

    buildFeatures {
        dataBinding true
    }

定义颜色值

colors.xml文件里面

    <!-- 文本主色调 -->
    <color name="app_textTheme">@color/white</color>
    <!-- 文本选中颜色 -->
    <color name="app_textNormal">#FF1D2835</color>
    <!-- 条目背景色 -->
    <color name="app_BackgroundColor">#FF1C1C28</color>
    <!-- 控件选中默认颜色 -->
    <color name="app_colorAccent">#FF1D2835</color>    

drawable文件夹下定义两个文件 文本的选中和为未选中效果:textview_selector_textcolor 背景的选中和为未选中效果:textview_selector_backgroundcolor

<?xml version="1.0" encoding="utf-8"?>
<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>
<?xml version="1.0" encoding="utf-8"?>
<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>

设置BindingAdapter

/** 设置 [v] 的选中状态为 [selected] */
@BindingAdapter("android:bind_selected")
fun setViewSelected(v: View, selected: Boolean?) {
    if (v.isSelected == selected) {
        return
    }
    v.isSelected = selected.condition
}

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"/>

ViewModel

 /** 当前postTypeId */
    val currentPostTypeId : ObservableInt = ObservableInt(0)
//点击事件下调用

使用方法

 currentPostTypeId.set(item.id!!)

上面只是核心代码 由于我是配合recyclerview使用的,adapter的代码我就不贴了,就是把viewModel和item(实体类的数据)传入就可以了,很简单,如果小白实在不理解就评论留言叭!
关键词:DataBinding 双向绑定

效果图

在这里插入图片描述