replace Image Span - Android android.text

Android examples for android.text:SpannableString

Description

replace Image Span

Demo Code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;

public class Main {

  public static SpannableString replaceImageSpan(CharSequence charSequence, String regPattern, Drawable drawable) {
    SpannableString ss = charSequence instanceof SpannableString ? (SpannableString) charSequence
        : new SpannableString(charSequence);
    try {/*  ww  w.  ja  v a  2  s.  co m*/
      ImageSpan is = new ImageSpan(drawable);
      Pattern pattern = Pattern.compile(regPattern);
      Matcher matcher = pattern.matcher(ss);
      while (matcher.find()) {
        String key = matcher.group();
        ss.setSpan(is, matcher.start(), matcher.start() + key.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
      }
    } catch (Exception ex) {
      Log.e(TAG, ex.toString());
    }

    return ss;
  }

}

Related Tutorials