Android:使用TextView.setText()为字符串着色部分?

时间:2011-02-04 11:13:06

标签: android textview

我希望通过.setText(“”)方法更改TextView视图的文本,同时也为文本的一部分着色(或使其变为粗体,斜体,透明等),而不是其余部分。例如:

title.setText("Your big island <b>ADVENTURE!</b>";

我知道上面的代码不正确,但它有助于说明我想要实现的目标。我该怎么做?

16 个答案:

答案 0 :(得分:190)

使用spans

示例:

final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");

// Span to set text color to some RGB value
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); 

// Span to make text bold
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); 

// Set the text color for first 4 characters
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

// make them also bold
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

yourTextView.setText(sb);

答案 1 :(得分:45)

title.setText(Html.fromHtml("Your big island <b>ADVENTURE!</b>")); 

答案 2 :(得分:24)

我希望这可以帮助你(它适用于多语言)。

<string name="test_string" ><![CDATA[<font color="%1$s"><b>Test/b></font>]]> String</string>

在你的java代码上,你可以这样做:

int color = context.getResources().getColor(android.R.color.holo_blue_light);
String string = context.getString(R.string.test_string, color);
textView.setText(Html.fromHtml(string));

这样,只有&#34;测试&#34;部分将着色(和粗体)。

答案 3 :(得分:16)

这是一个示例,它将查找所有出现的单词(不区分大小写),并将其着色为红色:

String notes = "aaa AAA xAaax abc aaA xxx";
SpannableStringBuilder sb = new SpannableStringBuilder(notes);
Pattern p = Pattern.compile("aaa", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(notes);
while (m.find()){
    //String word = m.group();
    //String word1 = notes.substring(m.start(), m.end());

    sb.setSpan(new ForegroundColorSpan(Color.rgb(255, 0, 0)), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
editText.setText(sb);

答案 4 :(得分:8)

您可以使用Spannable为文本的某些部分提供某些方面。如果你愿意,我可以查一个例子。

啊,就在stackoverflow上。

TextView TV = (TextView)findViewById(R.id.mytextview01); 
Spannable WordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(WordtoSpan);

答案 5 :(得分:4)

如果您想使用HTML,则需要使用TextView.setText(Html.fromHtml(String htmlString))

如果你想经常/重复这样做,你可能会看一下我写的一个类(SpannableBuilder),因为Html.fromHtml()不是很有效(它使用一个大的xml解析机制)内)。它在blog posting中进行了描述。

答案 6 :(得分:2)

您可以连接两个或多个Spans。这种方式更容易使用长度值为动态文本着色。

SpannableStringBuilder span1 = new SpannableStringBuilder("Android");
ForegroundColorSpan color1=new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary));
span1.setSpan(color1, 0, span1.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

SpannableStringBuilder span2 = new SpannableStringBuilder("Love");
ForegroundColorSpan color2=new ForegroundColorSpan(getResources().getColor(R.color.colorSecondary));
span2.setSpan(color2, 0, span2.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

Spanned concatenated=(Spanned) TextUtils.concat(span1," => ",span2);

SpannableStringBuilder result = new SpannableStringBuilder(concatenated);

TextView tv = (TextView) rootView.findViewById(R.id.my_texview);
tv.setText(result, TextView.BufferType.SPANNABLE);

答案 7 :(得分:2)

&#13;
&#13;
            String str1 = "If I forget my promise to ";
            String penalty = "Eat breakfast every morning,";
            String str2 = " then I ";
            String promise = "lose my favorite toy";
           

            String strb = "<u><b><font color='#081137'>"+ penalty +",</font></b></u>";
            String strc = "<u><b><font color='#081137'>"+ promise + "</font></b></u>";
            String strd = str1 +strb+ str2 + strc;
           tv_notification.setText(Html.fromHtml(strd));
&#13;
&#13;
&#13;

或使用此代码:

&#13;
&#13;
    SpannableStringBuilder builder = new SpannableStringBuilder();
            SpannableString text1 = new SpannableString(str1);
            text1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.silver)), 0, str1.length() - 1, 0);
            builder.append(text1);

            SpannableString text2 = new SpannableString(penalty);
            text2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.midnight)), 0, penalty.length(), 0);
            text2.setSpan(new UnderlineSpan(), 0, penalty.length(), 0);
            builder.append(text2);

            SpannableString text3 = new SpannableString(str2);
            text3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.silver)),0, str2.length(), 0);
            builder.append(text3);


            SpannableString text4 = new SpannableString(promise);
            text4.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.midnight)), 0, promise.length(), 0);
            text4.setSpan(new UnderlineSpan(),0, promise.length(), 0);
            builder.append(text4);

          tv_notification.setText(builder);
&#13;
&#13;
&#13;

答案 8 :(得分:2)

public static void setColorForPath(Spannable spannable, String[] paths, int color) {
    for (int i = 0; i < paths.length; i++) {
        int indexOfPath = spannable.toString().indexOf(paths[i]);
        if (indexOfPath == -1) {
            continue;
        }
        spannable.setSpan(new ForegroundColorSpan(color), indexOfPath,
                indexOfPath + paths[i].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

使用

Spannable spannable = new SpannableString("Your big island ADVENTURE");
Utils.setColorForPath(spannable, new String[] { "big", "ADVENTURE" }, Color.BLUE);

textView.setText(spannable);

enter image description here

答案 9 :(得分:2)

我喜欢通过逐个附加不同的跨度来使用SpannableStringBuilder,而不是通过计算字符串长度来调用setSpan

as:(Kotlin代码)

val amountSpannableString = SpannableString("₹$amount").apply {
  // text color
  setSpan(ForegroundColorSpan("#FD0025".parseColor()), 0, length, 0)
  // text size
  setSpan(AbsoluteSizeSpan(AMOUNT_SIZE_IN_SP.spToPx(context)), 0, length, 0)
  // font medium
  setSpan(TypefaceSpan(context.getString(R.string.font_roboto_medium)), 0, length, 0)
}

val spannable: Spannable = SpannableStringBuilder().apply {
  // append the different spans one by one
  // rather than calling setSpan by calculating the string lengths
  append(TEXT_BEFORE_AMOUNT)
  append(amountSpannableString)
  append(TEXT_AFTER_AMOUNT)
}

Result

答案 10 :(得分:1)

使用此代码有用

TextView txtTest = (TextView) findViewById(R.id.txtTest);
txtTest.setText(Html.fromHtml("This is <font color="#ff4343">Red</font> Color!"));

答案 11 :(得分:1)

如果您使用的是Kotlin,可以使用android-ktx

执行以下操作
val title = SpannableStringBuilder()
        .append("Your big island ")
        .bold { append("ADVENTURE") } 

title.text = s 

boldSpannableStringBuilder上的扩展功能。您可以查看文档here以获取可以使用的操作列表。

另一个例子:

val ssb = SpannableStringBuilder()
            .color(green, { append("Green text ") })
            .append("Normal text ")
            .scale(0.5, { append("Text at half size " })
            .backgroundColor(green, { append("Background green") })

green是解析的RGB颜色。

甚至可以嵌套跨度,以便最终得到类似嵌入式DSL的东西:

bold { underline { italic { append("Bold and underlined") } } }

您需要在应用模块级别build.gradle中使用以下内容才能使其正常工作:

repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:0.3'
}

答案 12 :(得分:0)

article中有许多有用的示例。

答案 13 :(得分:0)

Html.fromHtml已被弃用

改为使用HtmlCompat

HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY)

答案 14 :(得分:0)

如果您不想在较低的 SDK 版本上遇到麻烦,请使用带有 SpannableStringBuilderForegroundColorSpanBackgroundColorSpan,因为 HtmlCompat.fromHtml 颜色样式不适用于较旧的 Android 版本。

答案 15 :(得分:0)

你可以在 Kotlin 中使用扩展函数

fun CharSequence.colorizeText(
    textPartToColorize: CharSequence,
    @ColorInt color: Int
): CharSequence = SpannableString(this).apply {
    val startIndexOfText = this.indexOf(textPartToColorize.toString())
    setSpan(ForegroundColorSpan(color), startIndexOfText, startIndexOfText.plus(textPartToColorize.length), 0)
}

用法:

val colorizedText = "this text will be colorized"
val myTextToColorize = "some text, $colorizedText continue normal text".colorizeText(colorizedText,ContextCompat.getColor(context, R.color.someColor))