Android中 TextView设置颜色无效的问题

时间:2025-01-31 08:55:35

今天在给TextView设置颜色的时候遇到一个问题,怎么设置他的颜色,他都是显示一种颜色。

如下是我设置的代码:

            ();

由于不是用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 .#getColor(Context, int) getColor}.
     *
     * @see #setTextColor(ColorStateList)
     * @see #getTextColors()
     *
     * @attr ref #TextView_textColor
     */
    @
    public void setTextColor(@ColorInt int color) {
        mTextColor = (color);
        updateTextColors();
    }

真是一口老血都喷出来了,我传了一个resource ID进去,源码告诉我们要用getColor()方法,于是

(().getColor()); 

这样就大功告成。

但是我在查看源码的同时意外发现:

     /**
     * Sets the text color.
     *
     * @see #setTextColor(int)
     * @see #getTextColors()
     * @see #setHintTextColor(ColorStateList)
     * @see #setLinkTextColor(ColorStateList)
     *
     * @attr ref #TextView_textColor
     */
    @
    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 #TextView_textColor
     */
    public final ColorStateList getTextColors() {
        return mTextColor;
    }

结合第一段代码的注释,如果你想要设置文字颜色随状态可变的话,第一种设置方法不管怎么样都会默认的颜色

因此想要动态设置的话,我们应该

( ().getColorStateList( .text_color_pressed) );