TextView 的 Xamarin 颜色部分

Xamarin color part of a TextView

我希望我的 TextView 在我的 ViewSwitcher 中每隔一行在绿色和白色之间切换颜色。我弄清楚了如何更改颜色,但只能使用以下方法更改整个 TextView 的颜色:

SetTextColor()

您需要使用 TextView 的 TextFormatted 属性。您可以在 Xamarin 论坛上找到一些示例:https://forums.xamarin.com/discussion/9403/setting-a-textview-to-a-spannable-string

I want my TextView in my ViewSwitcher to switch colors between green and white every new line. I figure out how to change the color, but only of the entire TextView

您可以使用 TextFormattedAndroid.Text.SpannableString 一起设置颜色:

int lineCount = tvResult.LineCount;
SpannableString spannableText =new SpannableString(tvResult.Text);
for (int i = 0; i < lineCount; i++)
{
   int start=tvResult.Layout.GetLineStart(i);
   int end = tvResult.Layout.GetLineEnd(i);
   if (i % 2 == 1)
   {
       spannableText.SetSpan(new ForegroundColorSpan(Android.Graphics.Color.Yellow), start, end, SpanTypes.Composing);
   }
   else
   {
       spannableText.SetSpan(new ForegroundColorSpan(Android.Graphics.Color.Green), start, end,SpanTypes.Composing);
   }
}
tvResult.TextFormatted = spannableText;

注意:tvResult 只是一个 TextView 控件。