0%

Android在代码里设置TextView随点击状态改变文字颜色

相信大家在开发中经常会用到按钮随点击状态改变背景、改变文字颜色的需求,TextView随点击状态改变文字颜色我们一般的做法是在res目录下新建color文件夹,然后在color文件下创建资源文件如下:

1
2
3
4
5
6
res/color/tv_color.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#123456"/>
<item android:state_pressed="false" android:color="#ff0000"/>
</selector>

在布局中使用:

1
2
3
4
5
6
<TextView 
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"
android:textColor="@color/text_color"/>

但是我们有时候可能会遇到在代码里去设置TextView的字体颜色随着点击状态改变。那在代码里如何设置呢?
正常我们在代码里设置TextView的字体颜色是这样的:

1
2
TextView textview = (TextView) findViewById(R.id.text);
textview.setTextColor(getResources().getColor(R.color.textColor));

那我们是不是也可以这样来设置呢?经试验这样设置文字随状态改变颜色是没有效果的。那应该怎样设置呢?我们发现TextView的setTextColor有两个方法,一个就是上面我们使用的这种,还有一种参数是一个ColorStateList对象,跟着这个类名发现好像就是我们想要的。来看一下ColorStateList这个类new ColorStateList(int[][] states, int[] colors)有两个参数,根据参数名一个是状态二维数组一个是颜色值数组。我们来试一下:

1
2
3
TextView textview = (TextView) findViewById(R.id.text);
ColorStateList cls = new ColorStateList(new int[][]{{android.R.attr.state_pressed},{0}}, new int[]{Color.RED,Color.BLUE});
textview.setTextColor(cls);

ColorStateList的第一个参数代表状态第二参数colors跟第一个参数一一对应。经测试完全正确。
其实还可以这么做:直接从xml转化成ColorStateList 如下:

1
2
3
TextView textview = (TextView) findViewById(R.id.text);
ColorStateList csl=(ColorStateList)getResources().getColorStateList(R.color.text_color);
textview.setTextColor(cls);

这样也能实现我们想要的效果,R.color.text_color就是我们上面写好的状态对应颜色的配置。
最后需要注意的事,如果给TextView配置了随状态改变颜色需要在代码里设置TextView的点击事件监听或者在布局里面加上android:clickable=”true”属性否则没有效果。如果你是对TextView的父布局设置了监听需要TextView随着父布局状态改变而改变则要在布局里面的TextView上加上一个属性:android:duplicateParentState=”true”

 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!