您的位置:首页 > 移动开发 > Android开发

Android可动态改变compoundDrawable颜色的TextView

2016-03-01 14:15 429 查看
常常可以看到,许多应用的TabItem都是以Icon+Text的形式存在,例如微信,京东。

当tabItem被置为selected状态的时候,icon和文字的颜色会发生变化。如下图所示:



对于这种图片+文字的排版方式我们可以通过一个TextView实现

<TextView
android:drawableTop="@drawable/ic_front_page"
android:text="首页"
/>

TextView处于Selected状态时,图片的颜色变化可以通过替换图片实现,这种实现我们需要准备一个selector文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/ic_front_page_selected" />
<item android:state_selected="true" android:drawable="@drawable/ic_front_page_selected" />
<item android:state_focused="false" android:drawable="@drawable/ic_front_page"/>
</selector>
考虑到包体积和灵活性,采用两张图片似乎有些麻烦,如果能只用一张图片就更好了。当Normal和Selected两个状态的图片只有颜色不一致时,可以通过ColorFilter来实现换色的功能:
public void setDrawableColor(int color) {
Drawable[] drawables = this.getCompoundDrawables();
for (int i = 0, size = drawables.length; i < size; i++) {
if (null != drawables[i]) {
drawables[i].setColorFilter(new PorterDuffColorFilter(color,
PorterDuff.Mode.SRC_IN));
}
}
}这样,我们成功的节约了一张图片并增强了灵活性,可以将图片的前景色替换为任意色彩。当然,还可以配合TextView本身的setTextColor方法组合设置文本和图片颜色,满足多样性的需求。



全部代码如下:

public class TabItem extends TextView {

public TabItem(Context context) {
this(context, null);
}

public TabItem(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public TabItem(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray appearance = context.obtainStyledAttributes(attrs,
R.styleable.TabItem, defStyleAttr, 0);
if (appearance != null) {
int textColor = 0;
int drawableColor = 0;
int n = appearance.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = appearance.getIndex(i);
switch (attr) {
case R.styleable.TabItem_tinColor:
mTintColor = appearance.getColor(attr, 0);
setTintColor(tintColor);
break;
case R.styleable.TabItem_textColor:
textColor = appearance.getColor(attr, textColor);
setTextColor(textColor);
break;
case R.styleable.TabItem_drawableColor:
drawableColor = appearance.getColor(attr, drawableColor);
setDrawableColor(drawableColor);
break;
}
}
appearance.recycle();
}
}

/**
* 文字和图片都上色
*/
public void setTintColor(int color) {
setTextColor(color);
setDrawableColor(color);
}

/**
* 图片上色
*/
public void setDrawableColor(int color) {
Drawable[] drawables = this.getCompoundDrawables();
for (int i = 0, size = drawables.length; i < size; i++) {
if (null != drawables[i]) {
drawables[i].setColorFilter(new PorterDuffColorFilter(color,
PorterDuff.Mode.SRC_IN));
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android开发 textview