是否有可能在TextView中设置文本跨度的颜色?
我想做一些类似于Twitter应用程序的事情,其中一部分文本是蓝色的。见下图:
(来源:twimg.com)
是否有可能在TextView中设置文本跨度的颜色?
我想做一些类似于Twitter应用程序的事情,其中一部分文本是蓝色的。见下图:
(来源:twimg.com)
当前回答
通过传递String和Color在文本上设置颜色:
private String getColoredSpanned(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
通过调用下面的代码设置TextView / Button / EditText等文本:
TextView:
TextView txtView = (TextView)findViewById(R.id.txtView);
获取彩色字符串:
String name = getColoredSpanned("Hiren", "#800000");
在TextView上设置文本:
txtView.setText(Html.fromHtml(name));
Done
其他回答
我也有同样的问题。 @Dano的回答绝对正确。但这对我没用。 之后,我发现问题,我已经添加ClickableSpan。它会把我的颜色改成另一种颜色(强调色)
问题
当你在ForegroundColorSpan或UnderlineSpan后添加ClickableSpan时,SpannableStringBuilder将不会改变颜色和undline。
解决方案
1. 与ClickableSpan
你可以覆盖ClickableSpan内部的updateDrawState方法。 在updateDrawState方法中,您应该删除超级回调。 之后,你应该根据需要修改你的文本绘制。
2. 没有ClickableSpan
添加ForegroundColorSpan来改变文本颜色 Add UnderlineSpan在文本中添加下划线。
下面的内容非常适合我
tvPrivacyPolicy = (TextView) findViewById(R.id.tvPrivacyPolicy);
String originalText = (String)tvPrivacyPolicy.getText();
int startPosition = 15;
int endPosition = 31;
SpannableString spannableStr = new SpannableString(originalText);
UnderlineSpan underlineSpan = new UnderlineSpan();
spannableStr.setSpan(underlineSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(Color.BLUE);
spannableStr.setSpan(backgroundColorSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
StyleSpan styleSpanItalic = new StyleSpan(Typeface.BOLD);
spannableStr.setSpan(styleSpanItalic, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tvPrivacyPolicy.setText(spannableStr);
以上代码的输出
如果你想要更多的控制,你可能想检查TextPaint类。下面是如何使用它:
final ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(final View textView) {
//Your onClick code here
}
@Override
public void updateDrawState(final TextPaint textPaint) {
textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
textPaint.setUnderlineText(true);
}
};
使用kotlin-ktx,您可以轻松实现这一点
bindView?.oneTimePasswordTitle?.text = buildSpannedString {
append("One Time Password ")
inSpans(
ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
){
append(" (As Registered Email)")
}
}
在某些情况下可以使用的另一种方法是在接受Spannable的视图的属性中设置链接颜色。
例如,如果你的Spannable将用于TextView,你可以在XML中设置链接颜色:
<TextView
android:id="@+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorLink="@color/your_color"
</TextView>
你也可以在代码中使用:
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);