qq聊天介面七:表情的傳送接收(用富文字現實)
阿新 • • 發佈:2019-02-04
先定義一個包含反射的ImageGettter
/**
* 用於解析富文字中的表情圖片
*/
mImageGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Class clazz = R.mipmap.class;
try {
Field field = clazz.getDeclaredField(source);
int sourceId = field.getInt(field);
Drawable drawable = getResources().getDrawable(sourceId);
drawable.setBounds(0 , 0, 50, 50);
return drawable;
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
};
將ImageGetter傳遞到adapter
messageAdapter = new MessageAdapter(messages, inflater, mImageGetter);
/**
* 點選表情時,將富文字新增到edittext中
*/
mGridViewFace.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Spanned spanned = Html.fromHtml("<img src='" + faces.get(position).getName() + "'/>", mImageGetter, null);
mEditTextMsg.getText().insert(mEditTextMsg.getSelectionStart(), spanned);
}
});
將富文字轉換為String並傳入moudel
messageSend.setMassageContent(filterHtml(Html.toHtml(mEditTextMsg.getText())));
messages.add(messageSend);
/*
用正則表示式過濾掉無關的文字
*/
public String filterHtml(String str) {
str = str.replaceAll("<(?!br|img)[^>]+>", "").trim();
return str;
}
在adapter用傳入的imagegetter解析:圖片
vhRight.mTextViewSend.setText(Html.fromHtml(message.getMassageContent(), mImageGetter, null));
完成任務!!!