TextView:无法在运行时更改文本颜色

Mis*_*ith 2 android colors textview

这是我在此的头一篇博文.我要TextView's在运行时更改文本颜色.有一个方法TextView.setTextColor(int),但它不适用于不在资源中的int值.

例如,在运行时计算的颜色(例如0xFF0000 (RGB),不存在)R.color不起作用.该TextView不会被渲染.
我已经看过这个Android的源代码,有两种方法,它们都不接受rgb int values作为参数:

/**
 * Sets the text color for all the states (normal, selected,
 * focused) to be this color.
 *
 * @attr ref android.R.styleable#TextView_textColor
 */
@android.view.RemotableViewMethod
public void setTextColor(int color) {
    mTextColor = ColorStateList.valueOf(color);
    updateTextColors();
}

/**
 * Sets the text color.
 *
 * @attr ref android.R.styleable#TextView_textColor
 */
public void setTextColor(ColorStateList colors) {
    if (colors == null) {
        throw new NullPointerException();
    }

    mTextColor = colors;
    updateTextColors();
}
Run Code Online (Sandbox Code Playgroud)

所以没有办法做到这一点?也许延伸TextView

提前致谢.

Dee*_*eeV 6

我认为问题可能是你没有设置颜色的alpha值.

TextView.setTextColor()不接受0xRRGGBB值.相反,它接受0xAARRGGBB.无论什么时候你放"0xFF0000",你实际上给出的值"0x00FF0000"给它一个alpha值为"0",这就是为什么TextView不渲染.因此,尝试将其设置为0xFFFF0000而不是0xFF0000.

或者,您可以使用Android的Color类.方法"Color.rgb(int,int,int)"隐式指定alpha值为255,因此调用"Color.rgb(255, 0, 0)"应该为文本生成红色值.