com/xyz/customandroid/ TextViewWithImages .java:
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) {
Spannable s = getTextWithImages(getContext(), text);
super.setText(s, 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;
}
}
用:
在 res/layout/mylayout 中.xml:
<com.xyz.customandroid.TextViewWithImages
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF00"
android:text="@string/can_try_again"
android:textSize="12dip"
style=...
/>
请注意,如果将 TextViewWithImages.java放在 com/xyz/customandroid/ 以外的某个位置,则还必须更改上面的包名称。com.xyz.customandroid
在 res/values/strings 中.xml:
<string name="can_try_again">Press [img src=ok16/] to accept or [img src=retry16/] to retry</string>
其中 ok16.png 和 retry16.png 是 res/drawable/ 文件夹中的图标