很多时候需要给text设置点击字体颜色变化,最近做的项目有这个需求,不过得通过代码来动态写。
首先通过xml如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_selected="true" android:color="@color/red"/>
<item android:state_enabled="true" android:state_selected="false" android:color="@color/gray"/>
<item android:state_pressed="true" android:color="@color/red"/>
<item android:state_focused="true" android:color="@color/red"/>
<item android:color="@color/gray"/>
</selector>
只要在layout里面给textview设置textColor就好了。但是有时候不得不通过代码生成,所以可以写个工具类:
private static ColorStateList createColorStateList(String selected, String pressed, String normal) {
int[] colors = new int[] { Color.parseColor(selected), Color.parseColor(pressed), Color.parseColor(normal) };
int[][] states = new int[3][];
states[0] = new int[] { android.R.attr.state_selected};
states[1] = new int[] { android.R.attr.state_pressed};
states[2] = new int[] {};
ColorStateList colorList = new ColorStateList(states, colors);
return colorList;
}
接着在Java代码中设置textView.setTextColor(createColorStateList("#ffffffff", "#ffffffee", "#ff44e6ff"));
即可。