首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

无法在< 24中使用Html.fromText为文本视图设置多文本颜色

对于无法在<24中使用Html.fromText为文本视图设置多文本颜色的问题,可以采用以下解决方案:

  1. 使用SpannableString:可以通过使用SpannableString来设置文本视图的多个文本颜色。SpannableString是Android中一种可变的字符串,可以在字符串的不同部分应用不同的格式。

以下是一个示例代码:

代码语言:txt
复制
TextView textView = findViewById(R.id.text_view);

String text = "这是一段文本";
SpannableString spannableString = new SpannableString(text);

// 设置第一个字符为红色
spannableString.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

// 设置第二个字符为绿色
spannableString.setSpan(new ForegroundColorSpan(Color.GREEN), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

// 设置文本视图的文本为SpannableString
textView.setText(spannableString);
  1. 自定义TextView:可以通过继承TextView并重写其onDraw()方法来实现自定义文本颜色的效果。

以下是一个示例代码:

代码语言:txt
复制
public class CustomTextView extends TextView {
    private List<TextColorInfo> textColorInfos = new ArrayList<>();

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

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

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

    public void addTextColorInfo(int start, int end, int color) {
        textColorInfos.add(new TextColorInfo(start, end, color));
        invalidate();
    }

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

        // 绘制设置的文本颜色
        for (TextColorInfo info : textColorInfos) {
            getPaint().setColor(info.color);
            canvas.drawText(getText().toString(), info.start, info.end, info.x, info.y, getPaint());
        }
    }

    private static class TextColorInfo {
        private int start;
        private int end;
        private int color;
        private float x;
        private float y;

        public TextColorInfo(int start, int end, int color) {
            this.start = start;
            this.end = end;
            this.color = color;
        }
    }
}

使用示例:

代码语言:txt
复制
CustomTextView textView = findViewById(R.id.custom_text_view);
textView.setText("这是一段文本");
textView.addTextColorInfo(0, 1, Color.RED);
textView.addTextColorInfo(1, 2, Color.GREEN);

这两种方法都可以在<24中为文本视图设置多个文本颜色。请注意,这里没有提及任何腾讯云产品,因为问题与云计算领域的知识没有直接关联。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

8分11秒

谷歌DeepMindI和InstructPix2Pix人工智能以及OMMO NeRF视图合成

领券