今天在给TextView设置颜色的时候遇到一个问题,怎么设置他的颜色,他都是显示一种颜色。
如下是我设置的代码:
tvTreble.setTextColor(R.color.white);
由于不是用Androidstdio编译的代码,当时未发现错误,查看了源码:
/**
* Sets the text color for all the states (normal, selected,
* focused) to be this color.
*
* @param color A color value in the form 0xAARRGGBB.
* Do not pass a resource ID. To get a color value from a resource ID, call
* {@link android.support.v4.content.ContextCompat#getColor(Context, int) getColor}.
*
* @see #setTextColor(ColorStateList)
* @see #getTextColors()
*
* @attr ref android.R.styleable#TextView_textColor
*/
@android.view.RemotableViewMethod
public void setTextColor(@ColorInt int color) {
mTextColor = ColorStateList.valueOf(color);
updateTextColors();
}
真是一口老血都喷出来了,我传了一个resource ID进去,源码告诉我们要用getColor()方法,于是
tvTreble.setTextColor(this.getResources().getColor(R.color.white));
这样就大功告成。
但是我在查看源码的同时意外发现:
/**
* Sets the text color.
*
* @see #setTextColor(int)
* @see #getTextColors()
* @see #setHintTextColor(ColorStateList)
* @see #setLinkTextColor(ColorStateList)
*
* @attr ref android.R.styleable#TextView_textColor
*/
@android.view.RemotableViewMethod
public void setTextColor(ColorStateList colors) {
if (colors == null) {
throw new NullPointerException();
}
mTextColor = colors;
updateTextColors();
}
/**
* Gets the text colors for the different states (normal, selected, focused) of the TextView.
*
* @see #setTextColor(ColorStateList)
* @see #setTextColor(int)
*
* @attr ref android.R.styleable#TextView_textColor
*/
public final ColorStateList getTextColors() {
return mTextColor;
}
结合第一段代码的注释,如果你想要设置文字颜色随状态可变的话,第一种设置方法不管怎么样都会默认的颜色
因此想要动态设置的话,我们应该
tvTreble.setTextColor( this.getResources().getColorStateList( R.color.text_color_pressed) );