单个TextView与多个彩色文本

时间:2011-05-23 07:50:26

标签: android textview

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

18 个答案:

答案 0 :(得分:311)

是的,如果您使用String的{​​{1}}属性格式化html,则将其传递给方法font-color

Html.fromHtml(your text here)

答案 1 :(得分:152)

您可以在不使用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);

答案 2 :(得分:32)

您可以使用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);

在此示例中,您可以使用getResources().getColor(R.color.red)

替换0xFFFF0000

答案 3 :(得分:30)

我这样做了:

Check reference

通过传递字符串颜色文字

设置颜色

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));

完成

答案 4 :(得分:22)

使用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);

答案 5 :(得分:8)

嘿,伙计们我已经这样做了,试试吧

TextView textView=(TextView)findViewById(R.id.yourTextView);//init

//here I am appending two string into my textView with two diff colors.
//I have done from fragment so I used here getActivity(), 
//If you are trying it from Activity then pass className.this or this; 

textView.append(TextViewUtils.getColoredString(getString(R.string.preString),ContextCompat.getColor(getActivity(),R.color.firstColor)));
textView.append(TextViewUtils.getColoredString(getString(R.string.postString),ContextCompat.getColor(getActivity(),R.color.secondColor)));

在TextViewUtils类中添加此方法

 /***
 *
 * @param mString this will setup to your textView
 * @param colorId  text will fill with this color.
 * @return string with color, it will append to textView.
 */
public static Spannable getColoredString(String mString, int colorId) {
    Spannable spannable = new SpannableString(mString);
    spannable.setSpan(new ForegroundColorSpan(colorId), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    Log.d(TAG,spannable.toString());
    return spannable;
}

答案 6 :(得分:4)

我已经写了一些与此问题类似的其他问题的代码,但是这个问题有重复,所以我无法回答那里,所以我只是把我的代码放在这里,如果有人在寻找相同的要求。

这不是完全正常运行的代码,您需要进行一些小的更改才能使其正常工作。

以下是代码:

我使用了@Graeme使用spannable text的想法。

String colorfulText = "colorfulText";       
    Spannable span = new SpannableString(colorfulText);             

    for ( int i = 0, len = colorfulText.length(); i < len; i++ ){
        span.setSpan(new ForegroundColorSpan(getRandomColor()), i, i+1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                     
    }   

    ((TextView)findViewById(R.id.txtSplashscreenCopywrite)).setText(span);

随机颜色方法:

  private int getRandomColor(){
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

答案 7 :(得分:3)

@Swapnil Kotwal答案的科特琳版。

Android Studio 4.0.1,Kotlin 1.3.72

val greenText = SpannableString("This is green,")
greenText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someGreenColor), null), 0, greenText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.text = greenText

val yellowText = SpannableString("this is yellow, ")
yellowText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someYellowColor), null), 0, yellowText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(yellowText)

val redText = SpannableString("and this is red.")
redText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someRedColor), null), 0, redText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(redText)

答案 8 :(得分:2)

尽可能使用SpannableBuilder类而不是HTML格式,因为它比HTML格式解析更快。 查看我自己的基准测试&#34; SpannableBuilder vs HTML&#34;在Github 谢谢!

答案 9 :(得分:1)

试试这个:

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

答案 10 :(得分:1)

if (Build.VERSION.SDK_INT >= 24) {
     Html.fromHtml(String, flag) // for 24 API  and more
 } else {
     Html.fromHtml(String) // or for older API 
 }

for 24 API and more(flag)

public static final int FROM_HTML_MODE_COMPACT = 63;
public static final int FROM_HTML_MODE_LEGACY = 0;
public static final int FROM_HTML_OPTION_USE_CSS_COLORS = 256;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE = 32;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_DIV = 16;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_HEADING = 2;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST = 8;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM = 4;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH = 1;
public static final int TO_HTML_PARAGRAPH_LINES_CONSECUTIVE = 0;
public static final int TO_HTML_PARAGRAPH_LINES_INDIVIDUAL = 1;

More Info

答案 11 :(得分:1)

最好在字符串文件中使用该字符串,如下所示:

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

答案 12 :(得分:1)

使用 Kotlin 和 Extensions,您可以非常简单和干净地添加彩色文本:

使用此内容创建一个文件 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、扩展、一些验证和在扩展中获取颜色。

答案 13 :(得分:0)

很棒的答案!我能够使用Spannable来构建彩虹色文本(所以这可以针对任何颜色数组重复)。这是我的方法,如果它可以帮助任何人:

private Spannable buildRainbowText(String pack_name) {
        int[] colors = new int[]{Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE};
        Spannable word = new SpannableString(pack_name);
        for(int i = 0; i < word.length(); i++) {
            word.setSpan(new ForegroundColorSpan(colors[i]), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return word;
    }

然后我只是setText(buildRainboxText(pack_name)); 请注意,我传入的所有单词都不到15个字符,这只是重复5种颜色3次 - 您需要调整数组的颜色/长度以供您使用!

答案 14 :(得分:0)

从API 24开始,您有了FROM_HTML_OPTION_USE_CSS_COLORS,因此您可以在CSS中定义颜色,而不必一直用font color="重复颜色 更清晰-当您有一些html并要突出显示一些预定义标签时-您只需要在html顶部添加CSS片段

答案 15 :(得分:0)

2020年6月25日,@ canerkaseler

我想分享科特琳答案

fun setTextColor(tv:TextView, startPosition:Int, endPosition:Int, color:Int){
    val spannableStr = SpannableString(tv.text)

    val underlineSpan = UnderlineSpan()
    spannableStr.setSpan(
        underlineSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val backgroundColorSpan = ForegroundColorSpan(this.resources.getColor(R.color.agreement_color))
    spannableStr.setSpan(
        backgroundColorSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val styleSpanItalic = StyleSpan(Typeface.BOLD)
    spannableStr.setSpan(
        styleSpanItalic,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    tv.text = spannableStr
}

之后,调用上面的函数。您可以拨打多个电话:

setTextColor(textView, 0, 61, R.color.agreement_color)
setTextColor(textView, 65, 75, R.color.colorPrimary)

输出: 您可以看到下划线和不同的颜色。

@canerkaseler

答案 16 :(得分:0)

我不知道,因为这是可能的,但是您可以简单地将<font> </font>添加到string.xml中,这将自动更改每个文本的颜色。无需添加任何其他代码,例如可扩展文本等。

示例

<string name="my_formatted_text">
    <font color="#FF0707">THIS IS RED</font>
    <font color="#0B132B">AND NOW BLUE</font>
</string>

答案 17 :(得分:0)

制作通用功能来像这样转换字符串可跨度。

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