【问题标题】:How to change color of text between two different type of braces如何更改两种不同类型的大括号之间的文本颜色
【发布时间】:2023-03-07 23:15:01
【问题描述】:

我有一个字符串,例如:My (favourite) {website} is (stackoverflow)

我想改变花括号和粗括号之间的颜色,我该怎么办?

【问题讨论】:

  • 这能回答你的问题吗? Set color of TextView span in Android
  • 使用Spannable文本,如果字符以任何类型的大括号开头,检查前面的char是否等于起始大括号的结束大括号。然后将颜色从n 应用到n-1 char。
  • 你能给我举个例子吗?

标签: android


【解决方案1】:

这是通过创建一个SpannableStringBuilder 来完成的,如下所示:

SpannableStringBuilder builder = new SpannableStringBuilder();

String red = "this is red";
SpannableString redSpannable= new SpannableString(red);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
builder.append(redSpannable);

String white = "this is white";
SpannableString whiteSpannable= new SpannableString(white);
whiteSpannable.setSpan(new ForegroundColorSpan(Color.WHITE), 0, white.length(), 0);
builder.append(whiteSpannable);

textView.setText(builder, BufferType.SPANNABLE);

更多信息请看here

【讨论】:

    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2021-05-15
    • 2018-06-05
    • 2021-03-11
    相关资源
    最近更新 更多