正如标题所述,我想知道是否有可能在单个textview元素中实现两种不同的颜色。
正如标题所述,我想知道是否有可能在单个textview元素中实现两种不同的颜色。
textView.setText("textExample", BufferType.SPANNABLE)
val regex = Regex("Example")
val color = ContextCompat.getColor(requireContext(), R.color.red)
private fun applyTint(textView:TextView, regex:Regex, intColor:Int) {
val span : Spannable = textView.text.toSpannable()
val values = regex.findAll(textView.text)
for(value in values.iterator()){
val range = value.range
span.setSpan(
ForegroundColorSpan(intColor),
range.first,
range.last+1,
Spannable.SPAN_COMPOSING
)
}
}
applyTint(textView, regex, color)
结果是这样的:
如果您需要更多关于正则表达式的信息,请查阅文档https://developer.android.com/reference/java/util/regex/Pattern#summary-of-regular-expression-constructs
Kotlin中的构建器函数:
val text = buildSpannedString {
append("My red text")
setSpan(
ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.red)),
3,
6,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
textView?.setText(text)
创建一个通用函数,将您的字符串转换为可跨度的格式。
//pass param textviewid ,start,end,string
//R.color.Red it's your color you can change it as requirement
fun SpannableStringWithColor(view: TextView,start:Int,end:Int, s: String) {
val wordtoSpan: Spannable =
SpannableString(s)
wordtoSpan.setSpan(
ForegroundColorSpan(ContextCompat.getColor(view.context, R.color.Red)),
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
view.text = wordtoSpan
}
我们可以像这样根据需求在任何地方使用它。
SpannableStringWithColor(tvMobileNo,0,14,"Mobile Number : " + "123456789")
SpannableStringWithColor(tvEmail,0,5,"Email : " + "abc@gmail.com" "))
SpannableStringWithColor(tvAddress,0,8,"Address : " + "Delhi India")