Skip to content

Instantly share code, notes, and snippets.

@elevenetc
Last active July 28, 2017 01:00
Show Gist options
  • Save elevenetc/742e2beafe092962d1dd to your computer and use it in GitHub Desktop.
Save elevenetc/742e2beafe092962d1dd to your computer and use it in GitHub Desktop.
TextViewWithImages.java
//<string name="can_try_again">Press [img src=ok16/] to accept or [img src=retry16/] to retry</string>
//http://stackoverflow.com/questions/15352496/how-to-add-image-in-a-textview-text
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class TextViewWithImages extends TextView {
public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TextViewWithImages(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewWithImages(Context context) {
super(context);
}
@Override public void setText(CharSequence text, BufferType type) {
if (isInEditMode()) {
super.setText(text, type);
} else {
super.setText(getTextWithImages(getContext(), text), BufferType.SPANNABLE);
}
}
private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();
private static boolean addImages(Context context, Spannable spannable) {
Pattern refImg = Pattern.compile("\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E");
boolean hasChanges = false;
Matcher matcher = refImg.matcher(spannable);
while (matcher.find()) {
boolean set = true;
for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
if (spannable.getSpanStart(span) >= matcher.start()
&& spannable.getSpanEnd(span) <= matcher.end()
) {
spannable.removeSpan(span);
} else {
set = false;
break;
}
}
String resname = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
int id = context.getResources().getIdentifier(resname, "drawable", context.getPackageName());
if (set) {
hasChanges = true;
spannable.setSpan( new ImageSpan(context, id),
matcher.start(),
matcher.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
return hasChanges;
}
private static Spannable getTextWithImages(Context context, CharSequence text) {
Spannable spannable = spannableFactory.newSpannable(text);
addImages(context, spannable);
return spannable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment