5

Why can't use the same Span object to setSpan above twice?

SpannableString ss = new SpannableString("aaaaa[1]bbbb[1]cccc[1]");

I need to replace all the [1] with a image. If I use the following code, only the last one is replaced by the image:

etShow = (EditText) findViewById(R.id.show);
SpannableString ss = new SpannableString("aaaaa[1]bbbb[1]cccc[1]");
int[] starts = new int[3];
int[] ends = new int[3];
int h = 0;
int k = 0;
for (int i = 0; i < ss.length(); i++) {
    if (ss.charAt(i) == '[') {
    starts[h] = i;
    h++;
    } else if (ss.charAt(i) == ']') {
    ends[k] = i;
    k++;
    }
    }

Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
        d.setBounds(0, 0, 50, 50);
        ImageSpan im = new ImageSpan(d);

for(int i=0;i<3;i++){
        ss.setSpan(im, starts[i], ends[i]+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);   
        }
etShow.getText().insert(0, ss);

If change to the following code, all the [1] are replaced by the image.

Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
        d.setBounds(0, 0, 50, 50);
        ImageSpan im = new ImageSpan(d);
        ImageSpan im1 = new ImageSpan(d);
        ImageSpan im2 = new ImageSpan(d);
        //for(int i=0;i<3;i++){
//      ss.setSpan(im, starts[i], ends[i]+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        ss.setSpan(im, starts[0], ends[0]+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        ss.setSpan(im1, starts[1], ends[1]+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        ss.setSpan(im2, starts[2], ends[2]+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    //  }

How can explaint this?

Judy
  • 1,772
  • 6
  • 27
  • 48

2 Answers2

10

I suspect that the span objects wind up as keys of a HashMap, inside the Spanned representation. Hence, reusing the same span object has the effect of replacing its prior use with a new use.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
5

I read the Spannable source code these days and find this question by Google, so I want to paste some source code to answer this question.

The SpannableString implement by SpannableStringInternal and setSpan method is as follows.

/* package */ void setSpan(Object what, int start, int end, int flags) {
    ...
    int count = mSpanCount;
    Object[] spans = mSpans;
    int[] data = mSpanData;
    for (int i = 0; i < count; i++) {
        if (spans[i] == what) {
            int ostart = data[i * COLUMNS + START];
            int oend = data[i * COLUMNS + END];
            data[i * COLUMNS + START] = start;
            data[i * COLUMNS + END] = end;
            data[i * COLUMNS + FLAGS] = flags;
            sendSpanChanged(what, ostart, oend, nstart, nend);
            return;
        }
    }
    ...
}

When you pass same span by setSpan method, it will check if spans array have same one and replace old start and end value by news.

Bill Lv
  • 71
  • 1
  • 3