我有一个简单的TextView选框(在LinearLayout内)。我需要每个字母都有不同的颜色。有谁知道我怎么能做到这一点?文本是预先定义的,因此如果需要,我可以对所有内容进行硬编码。这是我的TextView
<TextView
style="@style/myFont"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.45"
android:ellipsize="marquee"
android:lines="1"
android:marqueeRepeatLimit="marquee_forever"
android:text="@string/my_text" />
说文字是“Hello world!我很高兴!”
答案 0 :(得分:2)
使用Html.fromHtml()并设置文字。
randomColor = https://stackoverflow.com/a/4246400/1008278
XML格式列表&gt;&gt; https://gist.github.com/VenomVendor/6857539修改为StringArray
String tempText = "Hello world! I am happy!"
String[] tempTextArr = string.split("");
String newText = "";
String[] colors = getResources().getStringArray(R.array.color_n);
for(int i = 0; i < tempTextArr.length; i++ )
{
if(!tempTextArr[i].equals(" "))
{
newText = newText + "<font color='"+colors[i]+"'>"+tempTextArr[i]+"</font>"
//newText = newText + "<font color='"+randomColor+"'>"+tempTextArr[i]+"</font>"
}
else{
newText = newText + " ";
}
}
tv.setText(Html.fromHtml(newText));
答案 1 :(得分:2)
你去:
class ColorSpan extends ReplacementSpan {
private LinearGradient shader;
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
float w = paint.measureText(text, start, end - start);
int num = end - start;
int[] colors = new int[num];
float[] positions = new float[num];
float cx = 0;
float[] hsv = {
0, 1, 1
};
for (int i = 0; i < num; i++) {
float cw = paint.measureText(text, start+i, start+i+1);
positions[i] = cx / w;
cx += cw;
hsv[0] = i * 360f / num;
colors[i] = Color.HSVToColor(255, hsv);
}
Log.d(TAG, "getSize c " + Arrays.toString(colors));
Log.d(TAG, "getSize p " + Arrays.toString(positions));
Log.d(TAG, "getSize w " + w);
shader = new LinearGradient(0, 0, w, 0, colors, positions, TileMode.CLAMP);
return (int) w;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
paint.setShader(shader);
canvas.drawText(text, start, end, x, y, paint);
}
}
在onCreate中测试:
TextView tv = new TextView(this);
tv.setTextSize(40);
SpannableStringBuilder b = new SpannableStringBuilder("Hello World!");
ColorSpan what = new ColorSpan();
b.setSpan(what, 0, b.length()-1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(b);
setContentView(tv);