mbm29414
mbm29414

Reputation: 11598

Can't get Spannable quite right

I'm trying to assemble a long bit of text (from several different pieces of data) as the contents of a TextView.

I'd like each line to have the following structure:

{piece 1} | {piece 2}

I'd like each "{piece 1} | " to be a light gray color. I'd like each "{piece 2}" to be a dark gray color.

I have defined both of these colors.

I'd like the entire label to be a custom font that I've added to my app.

Here's what I'm trying so far:

// regularTf is a Typeface created from a font added to this app
mItemCodesLabel.setTypeface(regularTf);
SpannableStringBuilder builder  = new SpannableStringBuilder();
ForegroundColorSpan ltGraySpan  = new ForegroundColorSpan(R.color.light_gray);
ForegroundColorSpan dkGraySpan  = new ForegroundColorSpan(R.color.dark_gray);
int index                       = 0;
for (int i = 0; i < codes.size(); i = i + 1) {
    ParseObject code            = codes.get(i);
    String value                = code.getString("value") + " | ";
    if (i > 0) {
        builder.append("\n");
        index                   = index + 1;
    }
    builder.append(value);
    builder.setSpan(ltGraySpan, index, index + value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    index                       = index + value.length();
    String loc                  = code.getString("location");
    builder.append(loc);
    builder.setSpan(dkGraySpan, index, index + loc.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    index                       = index + loc.length();
}
mItemCodesLabel.setText(builder, TextView.BufferType.SPANNABLE);

The text color for this label is set to R.color.dark_gray in my layout file.

The results that I'm seeing are somewhat confusing. I have two codes for an item, and the TextView looks like this:

{code 1 piece 1} | {code 1 piece 2} {code 2 piece 1} | {code 2 piece 2}

"{code 1 piece 1} | " is dark gray. The rest is light gray.

Based on several tutorials I've read on this topic, I don't see anything wrong with my code, but I'll admit that the whole "Spannable" topic still confuses me some. I'm coming from iOS, and Spannable seems a lot like NSAttributedString, but it seems like I'm missing something.

Upvotes: 2

Views: 702

Answers (1)

Durgadass S
Durgadass S

Reputation: 1098

We cannot use the same instance of Span to mark several parts of the text. Whenever setSpan() is called by passing a Span instance, the previous span marked by that instance is cleared. I think, by knowing this fact you could solve the problem.

Upvotes: 3

Related Questions