qq聊天界面七:表情的发送接收(用富文本现实)

先预览一下效果qq聊天界面七:表情的发送接收(用富文本现实)_第1张图片
源码地址:https://github.com/heinika/SimpleChatUI

先定义一个包含反射的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("", 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));

完成任务!!!

你可能感兴趣的:(界面,聊天,android,android)