androidspannablestringspannablestringbuilder

android - SpannableStringBuilder not working for mor than 2 phrase


I want to set multiple color on my textView and it has a lot of example on net, but it is not working for me :((( here is my code :

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

}

and here is my result :

enter image description here

where is my mistake???


Solution

  • I do not know why but when remove ForegroundColorSpan objects and use new ForegroundColorSpan every time in calling setColoredSpan() textView show the Spans in right way.

    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)) ," روز"));