是否有可能改变一个字符串多种颜色在Java中的文本颜色? [英] Is it possible to change the text color in a string to multiple colors in Java?

查看:139
本文介绍了是否有可能改变一个字符串多种颜色在Java中的文本颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是,是否有可能改变这段文字是蓝色的一文,以蓝色在一个字符串?必须有一种方式...

 <的TextView
    机器人:重力=左
    机器人:填充=3dip
    机器人:文本=。此文本白色蓝色文字。
    机器人:文字颜色=#FFFFFF
    机器人:TEXTSIZE =22dp/>
 

解决方案

是的,它的可能。为此,您需要使用<一个href="http://developer.android.com/reference/android/text/SpannableString.html"><$c$c>SpannableString和<一href="http://developer.android.com/reference/android/text/style/ForegroundColorSpan.html"><$c$c>ForegroundColorSpan.

这应该是这个样子:

  SpannableStringBuilder建设者=新SpannableStringBuilder();

串红=这是红色的;
SpannableString redSpannable =新SpannableString(红色);
redSpannable.setSpan(新ForegroundColorSpan(Color.RED),0,red.length(),0);
builder.append(redSpannable);

串白色=这是白;
SpannableString whiteSpannable =新SpannableString(白色);
whiteSpannable.setSpan(新ForegroundColorSpan(Color.WHITE),0,white.length(),0);
builder.append(whiteSpannable);

字符串蓝色=这是蓝色的;
SpannableString blueSpannable =新SpannableString(蓝色);
blueSpannable.setSpan(新ForegroundColorSpan(Color.BLUE),0,blue.length(),0);
builder.append(blueSpannable);

mTextView.setText(制造商,BufferType.SPANNABLE);
 

What I mean is, is it possible to change the text "This text is blue" to the color blue in a single string? There must be a way...

<TextView
    android:gravity="left"
    android:padding="3dip"
    android:text="This text is white. This text is blue."
    android:textColor="#ffffff"
    android:textSize="22dp"/>

解决方案

Yes, its possible. For this you need to use SpannableString and ForegroundColorSpan.

This should look something like this:

SpannableStringBuilder builder = new SpannableStringBuilder();

String red = "this is red";
SpannableString redSpannable= new SpannableString(red);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
builder.append(redSpannable);

String white = "this is white";
SpannableString whiteSpannable= new SpannableString(white);
whiteSpannable.setSpan(new ForegroundColorSpan(Color.WHITE), 0, white.length(), 0);
builder.append(whiteSpannable);

String blue = "this is blue";
SpannableString blueSpannable = new SpannableString(blue);
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(), 0);
builder.append(blueSpannable);

mTextView.setText(builder, BufferType.SPANNABLE);

这篇关于是否有可能改变一个字符串多种颜色在Java中的文本颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆