Xamarin c# Android:如何更改子字符串中的文本颜色?

3

我需要用不同的颜色突出字符串中的一些单词。然后将该字符串分配给TextView的Text属性。我没有找到一个简单有效的方法来实现这个。你能帮帮我吗?谢谢。Maddox

3个回答

2
textview.SetTextColor(Color.ParseColor("#787887"));
string character="Helloworld Developer";
string withoutspecialcharacter="Helloworld";
SpannableString spannable = new SpannableString(character);
spannable.SetSpan(new ForegroundColorSpan(Color.Red), character.IndexOf(withoutspecialcharacter), (character.IndexOf(withoutspecialcharacter)) + (withoutspecialcharacter.Length), SpanTypes.ExclusiveExclusive);

textview.TextFormatted = spannable ;

1

使用 SpannableString 可以实现该功能。

请查看 Xamarin文档 中的 SpannableString 链接1

请查看 Android文档 中的 SpannableString 链接2

示例

var textView = FindViewById<TextView>(Resource.Id.my_label);
var span = new SpannableString("My Label");

span.SetSpan(new ForegroundColorSpan(Color.Red), 0, 2, 0);  // "My" is red
span.SetSpan(new ForegroundColorSpan(Color.Blue), 3, 8, 0); // "Label" is blue
textView.SetText(span, TextView.BufferType.Spannable);

0

您可以将HTML标签转换为可跨度:

ISpanned html;
if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
    html = Html.FromHtml("<font color='red'> StackOverflow </font>", FromHtmlOptions.ModeLegacy);
else
    // Obsolete in N+
    html = Html.FromHtml("<font color='blue'> StackOverflow </font>");
textview.SetText(html, TextView.BufferType.Spannable);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接