我在开发中发现没有消息置顶这个功能,然后我公司要求开发个消息置顶的功能,所以就的手动写了。环信好多功能都要自己写,消息撤回,文件夹等等
思路
我就想能不能在每个消息里面设置个标识,来区分是否是置顶的消息,然后我找了下消息实体类EMConversation。其中就有两个方法getExtField()和setExtField(""),反正我也不管这是什么方法发,反正我就能存能取就够了。哈哈。。。
主要方法
1、getExtField();
2、setExtField("")


开始实战
1. 在你要添加的置顶方法,我的是ConversationListFragment类中setUpView()方法中定义的侧滑按钮
//置顶消息
EMConversation tobeDeleteCons = (EMConversation)conversationListView.getItemAtPosition(conversationListView.getPositionForView(view));
String isTop = tobeDeleteCons.getExtField();
//判断是否是置顶消息
if("toTop".equals(isTop)){
//取消置顶,就设置为其他的字符串
tobeDeleteCons.setExtField("false");
}else {
//把它设置为置顶的标识
tobeDeleteCons.setExtField("toTop");
}
//刷新消息列表
refresh();
2.找到数据源在添加消息前添加进列表中。我的是EaseConversationListFragment中setUpView()方法,
conversationList.addAll(loadConversationList());
conversationListView.init(conversationList);
这个是主要方法
/**
* load conversation list
*
* @return
+ */
protected List<EMConversation> loadConversationList(){
// get all conversations
Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
onHandleEMConversation(conversations);
//添加置顶消息
List<Pair<Long, EMConversation>> topList = new ArrayList<Pair<Long, EMConversation>>();
synchronized (conversations) {
for (EMConversation conversation : conversations.values()) {
if (conversation.getAllMessages().size() != 0 && conversation.getExtField().equals("toTop")) {
topList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
}
}
}
List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
/**
* lastMsgTime will change if there is new message during sorting
* so use synchronized to make sure timestamp of last message won't change.
*/
synchronized (conversations) {
for (EMConversation conversation : conversations.values()) {
if (conversation.getAllMessages().size() != 0 && !conversation.getExtField().equals("toTop")) {
sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
}
}
}
try {
// Internal is TimSort algorithm, has bug
sortConversationByLastChatTime(sortList);
} catch (Exception e) {
e.printStackTrace();
}
List<EMConversation> list = new ArrayList<EMConversation>();
//添加置顶消息
for (Pair<Long, EMConversation> topItem : topList) {
list.add(topItem.second);
}
for (Pair<Long, EMConversation> sortItem : sortList) {
list.add(sortItem.second);
}
return list;
}
3.在EaseConversationAdapter中加上一些信息
EMConversation conversation = getItem(position);
//判断是否置顶,置顶改变文字
String isTop = conversation.getExtField();
if("toTop".equals(isTop)){
holder.btnToTop.setText("取消置顶");
holder.list_itease_layout.setBackgroundResource(R.drawable.ease_mm_top_listitem);
}else {
holder.btnToTop.setText("置顶");
holder.list_itease_layout.setBackgroundResource(R.drawable.ease_mm_listitem);
}
到此就改造好了
网友评论