1

我想在我的 textView 上设置多种颜色,它在网上有很多例子,但它对我不起作用:(((这是我的代码:

public class MainActivity extends Activity {

ImageView profile_picture;
TextView ageTxt;
Bitmap bitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    ageTxt = (TextView) findViewById(R.id.age);
    ageTxt.setText(setAgeText("3" , "11" , "27"));
}

private SpannableStringBuilder setAgeText(String year , String month , String day)
{
    SpannableStringBuilder builder = new SpannableStringBuilder();
    ForegroundColorSpan numColor = new ForegroundColorSpan(Color.rgb(103, 6, 143));
    ForegroundColorSpan textColor = new ForegroundColorSpan(Color.rgb(2, 104, 121));

    builder.append(setColoredSpan(numColor , year));
    builder.append(setColoredSpan(textColor , " سال و "));
    builder.append(setColoredSpan(numColor ,month));
    builder.append(setColoredSpan(textColor ," ماه و "));
    builder.append(setColoredSpan(numColor ,day));
    builder.append(setColoredSpan(textColor ," روز"));
    return builder;
}

private SpannableString setColoredSpan(ForegroundColorSpan color , String string)
{
    SpannableString spanStr = new SpannableString (string);
    spanStr.setSpan(color , 0 , spanStr.length() , 0);
    return spanStr;
}

}

这是我的结果:

在此处输入图像描述

我的错在哪里???

4

1 回答 1

1

我不知道为什么,但是当删除ForegroundColorSpan对象并new ForegroundColorSpan每次调用setColoredSpan()textView 时都会以正确的方式显示 Spans。

builder.append(setColoredSpan(new ForegroundColorSpan(Color.rgb(103, 6, 143)) , year));
    builder.append(setColoredSpan(new ForegroundColorSpan(Color.rgb(2, 104, 121)) , " سال و "));
    builder.append(setColoredSpan(new ForegroundColorSpan(Color.rgb(103, 6, 143)) ,month));
    builder.append(setColoredSpan(new ForegroundColorSpan(Color.rgb(2, 104, 121)) ," ماه و "));
    builder.append(setColoredSpan(new ForegroundColorSpan(Color.rgb(103, 6, 143)) ,day));
    builder.append(setColoredSpan(new ForegroundColorSpan(Color.rgb(2, 104, 121)) ," روز"));
于 2017-03-27T10:19:30.390 回答