You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义TextView运行时文字颜色不生效,仅Android Studio设计模式有效

自定义TextView运行时无法修改文字颜色的解决方案

问题现象

自定义TextView在Android Studio设计模式下文字颜色显示正常,但运行时存在两个异常:

  • 布局文件中设置的android:textColor属性完全失效
  • 通过代码调用setTextColor()动态修改颜色也没有效果

问题原因

问题出在init()方法里的setTypeface(font_type)调用。直接使用无样式参数的setTypeface重载方法,会重置TextView内部的TextPaint对象,导致之前通过布局或代码设置的文字颜色被覆盖。

解决方案

使用带字体样式参数的setTypeface重载方法,保留原有字体样式的同时,避免重置颜色属性:

修改init()方法如下:

private void init() {
    Typeface font_type = Typeface.createFromAsset(getContext().getAssets(), "fonts/Action_Man_Bold.ttf");
    // 保留原字体样式,防止颜色被重置
    setTypeface(font_type, getTypeface() != null ? getTypeface().getStyle() : Typeface.NORMAL);
}

如果不需要保留原有字体样式,也可以先保存当前颜色,设置字体后再恢复:

private void init() {
    // 先保存当前文字颜色
    int currentColor = getCurrentTextColor();
    Typeface font_type = Typeface.createFromAsset(getContext().getAssets(), "fonts/Action_Man_Bold.ttf");
    setTypeface(font_type);
    // 恢复之前设置的颜色
    setTextColor(currentColor);
}

修改后的完整代码

public class CustomTextView extends androidx.appcompat.widget.AppCompatTextView {

    public CustomTextView(Context context) {
        super(context);
        init();
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        Typeface font_type = Typeface.createFromAsset(getContext().getAssets(), "fonts/Action_Man_Bold.ttf");
        setTypeface(font_type, getTypeface() != null ? getTypeface().getStyle() : Typeface.NORMAL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }
}

验证效果

修改完成后:

  1. 布局中设置的android:textColor="#FF0000"会在运行时正常显示红色
  2. 代码中动态执行customTextView.setTextColor(Color.BLUE)也能成功将文字改为蓝色

内容的提问来源于stack exchange,提问作者Afshin Izadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:54:50