正如标题所说,我想知道是否有可能在单个textview元素中实现两个不同颜色的字符。
当前回答
最好使用strings文件中的字符串,如下所示:
<string name="some_text">
<![CDATA[
normal color <font color=\'#06a7eb\'>special color</font>]]>
</string>
用法:
textView.text=HtmlCompat.fromHtml(getString(R.string.some_text), HtmlCompat.FROM_HTML_MODE_LEGACY)
其他回答
试试这个:
mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" + "<br />" +
"<small>" + description + "</small>" + "<br />" +
"<small>" + DateAdded + "</small>"));
你可以使用Spannable应用效果到你的TextView:
这是我的例子,只是一个TextView文本的第一部分上色(同时允许您动态设置颜色,而不是硬编码成字符串与HTML的例子!)
mTextView.setText("Red text is here", BufferType.SPANNABLE);
Spannable span = (Spannable) mTextView.getText();
span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
在这个例子中,你可以将0xFFFF0000替换为getResources().getColor(R.color.red)
芬兰湾的科特林:
@JvmStatic
@BindingAdapter(
"app:txt1",
"app:txt2",
"app:color1",
"app:color2",
requireAll = false
)
fun setColors(
txtView: AppCompatTextView,
txt1: String,
txt2: String,
color1: Int,
color2: Int
) {
txtView.setColors(txt1 = txt1, txt2 = txt2, color1 = color1, color2)
}
fun AppCompatTextView.setColors(txt1: String, txt2: String, color1: Int, color2: Int) {
val word: Spannable = SpannableString(txt1)
word.setSpan(
ForegroundColorSpan(ContextCompat.getColor(this.context, color1)),
0,
word.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
this.text = word
val wordTwo: Spannable = SpannableString(txt2)
wordTwo.setSpan(
ForegroundColorSpan(ContextCompat.getColor(this.context, color2)),
0,
wordTwo.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
this.append(wordTwo)
}
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:txt1="@{}"
app:txt2="@{}"
app:color1="@{}"
app:color2="@{}" />
我不知道,因为这是可能的,但你可以简单地添加<font> </font>到你的string.xml,这将自动改变每个文本的颜色。不需要添加任何额外的代码,如可扩展的文本等。
例子
<string name="my_formatted_text">
<font color="#FF0707">THIS IS RED</font>
<font color="#0B132B">AND NOW BLUE</font>
</string>
尽可能使用SpannableBuilder类而不是HTML格式,因为它比HTML格式解析更快。 在Github上查看我自己的基准测试“SpannableBuilder vs HTML” 谢谢!
推荐文章
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)
- 如何在新的材质主题中改变背面箭头的颜色?
- androidviewpager与底部点
- 相同的导航抽屉在不同的活动
- 如何从视图中获得托管活动?
- 单一的TextView与多种颜色的文本
- 如何在非活动类(LocationManager)中使用getSystemService ?
- 在清单中注册应用程序类?
- Android:从数组中编程创建旋转器
- Android命令行工具sdkmanager总是显示:警告:无法创建设置