正如标题所说,我想知道是否有可能在单个textview元素中实现两个不同颜色的字符。
当前回答
尽可能使用SpannableBuilder类而不是HTML格式,因为它比HTML格式解析更快。 在Github上查看我自己的基准测试“SpannableBuilder vs HTML” 谢谢!
其他回答
使用Kotlin和扩展,您可以添加彩色文本非常简单和干净:
创建一个TextViewExtensions文件。Kt和这个含量
fun TextView.append(string: String?, @ColorRes color: Int) {
if (string == null || string.isEmpty()) {
return
}
val spannable: Spannable = SpannableString(string)
spannable.setSpan(
ForegroundColorSpan(ContextCompat.getColor(context, color)),
0,
spannable.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
append(spannable)
}
现在很容易添加文本的颜色
textView.text = "" // Remove old text
textView.append("Red Text", R.color.colorAccent)
textView.append("White Text", android.R.color.white)
基本上与@Abdul Rizwan的答案相同,但使用Kotlin,扩展,一些验证和在扩展内部获得颜色。
是的,如果你用html的font-color属性格式化字符串,然后把它传递给方法html . fromhtml(你的文本在这里)
String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));
你可以在没有HTML的情况下打印多种颜色的行:
TextView textView = (TextView) findViewById(R.id.mytextview01);
Spannable word = new SpannableString("Your message");
word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(word);
Spannable wordTwo = new SpannableString("Your new message");
wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(wordTwo);
我不知道,因为这是可能的,但你可以简单地添加<font> </font>到你的string.xml,这将自动改变每个文本的颜色。不需要添加任何额外的代码,如可扩展的文本等。
例子
<string name="my_formatted_text">
<font color="#FF0707">THIS IS RED</font>
<font color="#0B132B">AND NOW BLUE</font>
</string>
使用SpannableStringBuilder
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);
SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);
推荐文章
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)
- 如何在新的材质主题中改变背面箭头的颜色?
- androidviewpager与底部点
- 相同的导航抽屉在不同的活动
- 如何从视图中获得托管活动?
- 单一的TextView与多种颜色的文本
- 如何在非活动类(LocationManager)中使用getSystemService ?
- 在清单中注册应用程序类?
- Android:从数组中编程创建旋转器
- Android命令行工具sdkmanager总是显示:警告:无法创建设置