封装使用ViewHolder模式的Adapter组件,及用其快速实现聊天界面
大家都对viewholder模式并不陌生吧,避免了重复调用findViewbyId,并对convertview进行重用。但是,开发中可能会有这样的困扰,每次在创建Adapter类时,总会有许多的重复代码,比如每次都要创建一个ViewHolder类等等。为了解决这种问题,封装了viewholder模式的EasyAdapter就应运而生。在保持adapter的优化的同时,减轻你每次都需要重复去造轮子,也让你只需关心model数据的变化。EasyAdapter下载地址(https://github.com/mapleyuan/EasyAdapterHelper)。简单的使用方法如下:
listView.setAdapter(new EasyAdapter(getApplicationContext(), R.layout.listview_item, datas) {
@Override
public void convert(BaseViewHolderHelper viewHolderHelper, String data) {
viewHolderHelper.setTextView(R.id.textView, data);
}
});
那假如我们要快速创建一个下面的聊天界面的adapter该如何做呢?
adapter代码示例如下:
public class ChatViewAdapter extends EasyAdapter {
public ChatViewAdapter(Context context, List<MessageModle> datas) {
super(context, datas, new EasyAdapter.IMultiItem<MessageModle>() {
@Override
public int getResource(int position, MessageModle doubleChatMessage) {
return doubleChatMessage.mIsFrom ? R.layout.chatview_list_right_item : R.layout.chatview_list_left_item;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position, MessageModle doubleChatMessage) {
return doubleChatMessage.mIsFrom ? 0 : 1;
}
});
}
@Override
public void convert(BaseViewHolderHelper viewHolderHelper, MessageModle data) {
if (data.mType == MessageModle.MESSAGE_TYPE_TEXT) {
viewHolderHelper.setTextView(R.id.chatview_maincontent_text_id, data.mContent);
viewHolderHelper.setVisibility(R.id.chatview_maincontent_image_id, View.GONE);
viewHolderHelper.setVisibility(R.id.chatview_maincontent_text_id, View.VISIBLE);
} else {
viewHolderHelper.setVisibility(R.id.chatview_maincontent_image_id, View.VISIBLE);
viewHolderHelper.setVisibility(R.id.chatview_maincontent_text_id, View.GONE);
}
}
public static class MessageModle {
public static final int MESSAGE_TYPE_TEXT = 1;
public static final int MESSAGE_TYPE_ATTACHMENT = 2;
boolean mIsFrom;
/**
* @see {@link #MESSAGE_TYPE_TEXT}
*/
int mType;
public String mContent;
public MessageModle(boolean isFrom, int type, String content) {
mIsFrom = isFrom;
mType = type;
mContent = content;
}
}
可以看到,我们只需要继承EasyAdapter类并实现其convert()方法,就可以直接使用了。假如你对这个项目有兴趣,欢迎下载使用(https://github.com/mapleyuan/EasyAdapterHelper),有任何建议也欢迎跟我交流。