android 点击后颜色没有变化是为什么 以下是具体代码。
public class HomeFragmentVM extends ViewModel {
@SuppressLint("StaticFieldLeak")
private HomeFragment fragment;
public static final String SORT_COLUMN_AUTO = "auto";
public static final String SORT_COLUMN_ACTIVE = "active";
public static final String SORT_COLUMN_DISTANCE = "distance";
public static final String SORT_COLUMN_MATCH = "match";
public static final String SORT_ICON_DOWN = "sort:icon:down";
public static final String SORT_ICON_UP = "sort:icon:up";
public final MutableLiveData<SearchForm> searchForm = new MutableLiveData<>();
@SuppressLint("StaticFieldLeak")
public View rootView;
private static class SearchForm {
public String sortType = "asc";
public String sortColumn = SORT_COLUMN_ACTIVE;
}
public HomeFragmentVM(HomeFragment fragment, View rootView) {
this.fragment = fragment;
this.rootView = rootView;
this.init();
}
private void init() {
this.searchForm.setValue(new SearchForm());
}
public int getSortTextColor(String sortColumn) {
SearchForm searchForm = this.searchForm.getValue();
int color = R.color.color_333;
int colorActive = R.color.color_red_1;
if (searchForm == null) {
return color;
}
if (searchForm.sortColumn.equals(sortColumn)) {
return colorActive;
}
return color;
}
public void handleSort(String column) {
SearchForm searchForm = this.searchForm.getValue();
if (searchForm.sortColumn.equals(column) && column.equals(SORT_COLUMN_AUTO)) {
return ;
}
if (searchForm.sortColumn.equals(column)) {
// 重复点击搜索项 - 取消排序
searchForm.sortColumn = null;
searchForm.sortType = null;
} else {
searchForm.sortColumn = column;
if (column.equals(SORT_COLUMN_AUTO)) {
searchForm.sortType = null;
} else {
if (searchForm.sortType == null) {
searchForm.sortType = "asc";
}
if (searchForm.sortType.equals("asc")) {
searchForm.sortType = "desc";
}
if (searchForm.sortType.equals("desc")) {
searchForm.sortType = null;
}
}
}
// 更新数据
this.searchForm.setValue(searchForm);
}
xml
视图如下:
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<data>
<import type="com.gv.yinyuan.app.android.consts.AppConsts"/>
<variable name="vm" type="com.gv.yinyuan.app.android.vm.HomeFragmentVM"/>
</data>
<TextView
style="@style/fragment_home_sort_text"
android:text="综合"
android:textColor='@{vm.getSortTextColor(vm.SORT_COLUMN_AUTO)}'
android:layout_marginEnd="10dp"
android:onClick='@{(view) -> vm.handleSort(vm.SORT_COLUMN_AUTO)}'
/>
</layout>
【相关推荐】
避免创建不需要的对象。
比如使用StringBuffer来代替很多个String相加的操作。
使用原始类型来代替包装类型,int比Integer占用更少的资源。
两个并行的属性数组,优于一个包含这两个属性的对象的数组。这个在设计数据容器的时候会有意义,比如类A有两个属性A(int, String),使用 int[] 和 String[] 优于 A[]。
使用常量代替enum。
少用包装类,能够使用原始类型的,就使用原始类型。