我的建议是使用Spannable
。
这是一个简短的使用方法,我打包供您使用。您只需传递TextView,全文和单个部分以从全文中重新着色。
可以将此方法放置到utils的类并调用它,只要你想要的,或保持在一个活动或片段(或其他任何地方),如果你在一个类中使用它:
public static void colorText(TextView view, final String fullText, final String whiteText) {
if (fullText.length() < whiteText.length()) {
throw new IllegalArgumentException("'fullText' parameter should be longer than 'whiteText' parameter ");
}
int start = fullText.indexOf(whiteText);
if (start == -1) {
return;
}
int end = start + whiteText.length();
SpannableStringBuilder finalSpan = new SpannableStringBuilder(fullText);
// finalSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(view.getContext(),R.color.your_own_color_code)), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
finalSpan.setSpan(new ForegroundColorSpan(Color.WHITE), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
view.setText(finalSpan);
}
您可以用' Html.fromHtml'或者'Spannable字符串'('ForegroundColorSpan') – Blackbelt
你可以显示它与我的代码?我如何使用这种格式? –
我尝试了几个foregroundcolorspans和spannables,它根本没有工作 –