对于无法在<24中使用Html.fromText为文本视图设置多文本颜色的问题,可以采用以下解决方案:
以下是一个示例代码:
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);
onDraw()
方法来实现自定义文本颜色的效果。以下是一个示例代码:
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;
}
}
}
使用示例:
CustomTextView textView = findViewById(R.id.custom_text_view);
textView.setText("这是一段文本");
textView.addTextColorInfo(0, 1, Color.RED);
textView.addTextColorInfo(1, 2, Color.GREEN);
这两种方法都可以在<24中为文本视图设置多个文本颜色。请注意,这里没有提及任何腾讯云产品,因为问题与云计算领域的知识没有直接关联。
领取专属 10元无门槛券
手把手带您无忧上云