简体   繁体   English

如何更改 TextView 部分的文本颜色?

[英]How to change text color of the part of the TextView?

I have simple textView controler on my application.我的应用程序上有简单的 textView 控制器。
On this textView i set the text "123456789" - the text color is black.在此 textView 上,我设置了文本“123456789” - 文本颜色为黑色。

I want that the three last digit ( 789 ) will be shown with red text color.我希望最后三位数字( 789 )将显示为红色文本颜色。

Is there any simple way to do it without using two textView controls有没有不使用两个 textView 控件的简单方法
(one will contain "123456" in black and second will contain "789" in red ) (一个将包含黑色的“123456”,第二个将包含红色的“789”)

Try This:尝试这个:

Set TextView as a HTML using SpannableTextView使用SpannableTextViewTextView设置为HTML

String text = "<font color='black'>123456</font><font color='red'>789</font>";
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);

您可以使用

myTextView.setText(Html.fromHtml(stringB + "<font color=red>" + stringA + "</font>);

You can use SpannableString is an excellent way to style strings in a TextView .您可以使用SpannableString是在TextView字符串样式的绝佳方式。

Demo 演示

SO Post 邮局

You can use this method你可以使用这个方法

public static final Spannable getColoredString(Context context, CharSequence text, int color) {
        Spannable spannable = new SpannableString(text);
        spannable.setSpan(new ForegroundColorSpan(color), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannable;
    }

then later you call is by using然后你打电话是通过使用

textview.append(getColoredString(this, "Hi!", ContextCompact.getColor(this, R.color.red)));
textview.append(getColoredString(this, "User", ContextCompact.getColor(this, R.color.green)));

You can either use HTML banners in your java class: Example:您可以在 Java 类中使用 HTML 横幅:示例:

 textElement.setText(Html.fromHtml("123456 <fontcolor='#FF0000'>789</font>"));

Or use CData format in your XML file: Example:或者在您的 XML 文件中使用 CData 格式:示例:

<string name="numbers"><![CDATA[123456<fontcolor="#FF0000">789</font>]]></string>

I hope that helped you ;)我希望对你有帮助;)

You can use this.你可以用这个。

textview.setText(Html.fromHtml(getString(R.string.stringname) + "" + " *" + "", Html.FROM_HTML_MODE_LEGACY)); textview.setText(Html.fromHtml(getString(R.string.stringname) + "" + " *" + "", Html.FROM_HTML_MODE_LEGACY));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM