是否有可能在TextView中设置文本跨度的颜色?
我想做一些类似于Twitter应用程序的事情,其中一部分文本是蓝色的。见下图:
(来源:twimg.com)
是否有可能在TextView中设置文本跨度的颜色?
我想做一些类似于Twitter应用程序的事情,其中一部分文本是蓝色的。见下图:
(来源:twimg.com)
当前回答
只是补充一个公认的答案,因为所有的答案似乎都在谈论android.graphics.Color only:如果我想要的颜色是在res/values/colors.xml中定义的呢?
例如,考虑colors.xml中定义的材质设计颜色:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="md_blue_500">#2196F3</color>
</resources>
(android_material_design_colors .xml是你最好的朋友)
然后使用contextcompast . getcolor (getContext(), R.color.md_blue_500),在这里您将使用Color。蓝色,所以:
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
就变成:
wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
我发现:
在Android中使用跨度- Michael Spitsin - Medium
其他回答
设置你的TextView的文本跨度,并为你的文本定义一个ForegroundColorSpan。
TextView textView = (TextView)findViewById(R.id.mytextview01);
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(wordtoSpan);
这是一个Kotlin扩展函数
fun TextView.setColouredSpan(word: String, color: Int) {
val spannableString = SpannableString(text)
val start = text.indexOf(word)
val end = text.indexOf(word) + word.length
try {
spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spannableString
} catch (e: IndexOutOfBoundsException) {
println("'$word' was not not found in TextView text")
}
}
使用它后,你已经设置你的文本到TextView,就像这样
private val blueberry by lazy { getColor(R.color.blueberry) }
textViewTip.setColouredSpan("Warning", blueberry)
在某些情况下可以使用的另一种方法是在接受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);
使用kotlin-ktx,您可以轻松实现这一点
bindView?.oneTimePasswordTitle?.text = buildSpannedString {
append("One Time Password ")
inSpans(
ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
){
append(" (As Registered Email)")
}
}
现在您可以使用CodeView库轻松地突出显示不同颜色的模式,例如,用您只需要编写的蓝色突出显示文本中的所有url
CodeView codeView = findViewById(R.id.codeview);
codeView.addSyntaxPattern(Patterns.WEB_URL, Color.BLUE);
codeView.setTextHighlighted(text);
CodeView存储库URL: https://github.com/amrdeveloper/codeview