自己弄了个自定义控件继承自TextView
package org.face;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spanned;
import android.util.AttributeSet;
import android.widget.TextView;
public class FaceTextView extends TextView {
private CharSequence text;
public FaceTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public FaceTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public FaceTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public CharSequence getText() {
return text == null ? "" : text;
}
@Override
public void setText(CharSequence text, BufferType type) {
this.text = text;
String cs = text.toString();
// 对表情符以img标记进行修饰,改用drawable显示出来
if (cs.contains(":-{1}quot;)) {
cs = cs.replace(":-{1}quot;, "<img src=\"confused\"/>");
}
Spanned span = Html.fromHtml(cs, new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable drawable = null;
String sourceName = getContext().getPackageName() + ":drawable/"
+ source;
int id = getResources().getIdentifier(sourceName, null, null);
if (id != 0) {
drawable = getResources().getDrawable(id);
if (drawable != null) {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
}
}
return drawable;
}
}, null);
super.setText(span, type);
}
}
这种方式是将text中字符替换成HTML标签,采用Html.fromHtml去解析.
布局文件main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="#FFFFFF">
<org.face.FaceTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="第六个:-$笑脸"/>
</LinearLayout>
上面代码需要看到效果需要有张confused的图片。
=>有人也采用SpannableString和ImageSpan类实现了添加图片的效果
这里我将它也贴上
你可以将上面FaceTextView类里面的setText(CharSequence text, BufferType type)方法内容替换下
Drawable drawable = getResources().getDrawable(R.drawable.confused);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
// 需要处理的文本,[smile]是需要被替代的文本
SpannableString spannable = new SpannableString(getText().toString()+"[smile]");
// 要让图片替代指定的文字就要用ImageSpan
ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
// 开始替换,注意第2和第3个参数表示从哪里开始替换到哪里替换结束(start和end)
// 最后一个参数类似数学中的集合,[5,12)表示从5到12,包括5但不包括12
spannable.setSpan(span, getText().length(),getText().length()+"[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
super.setText(spannable, type);
上面两种方式的缺陷是:gif图片显示出来的是个静态的,待研究.