正如标题所说,我想知道是否有可能在单个textview元素中实现两个不同颜色的字符。


当前回答

试试这个:

mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" + 
      "<small>" + description + "</small>" + "<br />" + 
      "<small>" + DateAdded + "</small>"));

其他回答

让普通函数转换你的字符串是可扩展的,像这样。

//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")

如果你想在strings.xml中给出文本颜色和文本大小,那么检查下面的代码:

<string name="txt_my_string">
    <font fgcolor='#CFD8DC' > Text with given color </font> // Custom text color
    <font size="14" > Text with given size </font> // Custom Text size
    <font fgcolor='#3A55EA' size="14" > Text with given color and size </font> // Custom text color and size
</string>

希望你能容易理解:)

我是这样做的:

通过传递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");
String surName = getColoredSpanned("Patel","#000080");

在TextView上设置两个不同颜色的字符串的文本:

txtView.setText(Html.fromHtml(name+" "+surName));

Done

自从API 24以来,你有FROM_HTML_OPTION_USE_CSS_COLORS,所以你可以在CSS中定义颜色,而不是一直重复使用font color=" 更清楚-当你有一些html,你想突出一些预定义的标签-你只需要在你的html顶部添加CSS片段

试试这个:

mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" + 
      "<small>" + description + "</small>" + "<br />" + 
      "<small>" + DateAdded + "</small>"));