注册

环信官方Demo源码分析及SDK简单应用-主界面的三个fragment-通讯录界面

环信官方Demo源码分析及SDK简单应用

环信官方Demo源码分析及SDK简单应用-ChatDemoUI3.0

环信官方Demo源码分析及SDK简单应用-LoginActivity
 
环信官方Demo源码分析及SDK简单应用-主界面的三个fragment-会话界面
 
环信官方Demo源码分析及SDK简单应用-主界面的三个fragment-通讯录界面
 
环信官方Demo源码分析及SDK简单应用-主界面的三个fragment-设置界面
 
环信官方Demo源码分析及SDK简单应用-EaseUI
 
环信官方Demo源码分析及SDK简单应用-IM集成开发详案及具体代码实现
 
刚才我们看了主界面的三个fragment中的第一个界面-会话界面,再来看通讯录界面。
 
通讯录界面
ContactListFragment


照例,我们来贴代码:
/**
* Copyright (C) 2016 Hyphenate Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hyphenate.chatuidemo.ui;

import java.util.Hashtable;
import java.util.Map;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chatuidemo.DemoHelper;
import com.hyphenate.chatuidemo.DemoHelper.DataSyncListener;
import com.hyphenate.chatuidemo.R;
import com.hyphenate.chatuidemo.db.InviteMessgeDao;
import com.hyphenate.chatuidemo.db.UserDao;
import com.hyphenate.chatuidemo.widget.ContactItemView;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.NetUtils;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

/**
* contact list
*
*/
public class ContactListFragment extends EaseContactListFragment {

private static final String TAG = ContactListFragment.class.getSimpleName();
private ContactSyncListener contactSyncListener;
private BlackListSyncListener blackListSyncListener;
private ContactInfoSyncListener contactInfoSyncListener;
private View loadingView;
private ContactItemView applicationItem;
private InviteMessgeDao inviteMessgeDao;

@SuppressLint("InflateParams")
@Override
protected void initView() {
super.initView();
@SuppressLint("InflateParams") View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.em_contacts_header, null);
HeaderItemClickListener clickListener = new HeaderItemClickListener();
applicationItem = (ContactItemView) headerView.findViewById(R.id.application_item);
applicationItem.setOnClickListener(clickListener);
headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
headerView.findViewById(R.id.chat_room_item).setOnClickListener(clickListener);
headerView.findViewById(R.id.robot_item).setOnClickListener(clickListener);
listView.addHeaderView(headerView);
//add loading view
loadingView = LayoutInflater.from(getActivity()).inflate(R.layout.em_layout_loading_data, null);
contentContainer.addView(loadingView);

registerForContextMenu(listView);
}

@Override
public void refresh() {
Map<String, EaseUser> m = DemoHelper.getInstance().getContactList();
if (m instanceof Hashtable<?, ?>) {
//noinspection unchecked
m = (Map<String, EaseUser>) ((Hashtable<String, EaseUser>)m).clone();
}
setContactsMap(m);
super.refresh();
if(inviteMessgeDao == null){
inviteMessgeDao = new InviteMessgeDao(getActivity());
}
if(inviteMessgeDao.getUnreadMessagesCount() > 0){
applicationItem.showUnreadMsgView();
}else{
applicationItem.hideUnreadMsgView();
}
}


@SuppressWarnings("unchecked")
@Override
protected void setUpView() {
titleBar.setRightImageResource(R.drawable.em_add);
titleBar.setRightLayoutClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// startActivity(new Intent(getActivity(), AddContactActivity.class));
NetUtils.hasDataConnection(getActivity());
}
});
//设置联系人数据
Map<String, EaseUser> m = DemoHelper.getInstance().getContactList();
if (m instanceof Hashtable<?, ?>) {
m = (Map<String, EaseUser>) ((Hashtable<String, EaseUser>)m).clone();
}
setContactsMap(m);
super.setUpView();
listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EaseUser user = (EaseUser)listView.getItemAtPosition(position);
if (user != null) {
String username = user.getUsername();
// demo中直接进入聊天页面,实际一般是进入用户详情页
startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", username));
}
}
});


// 进入添加好友页
titleBar.getRightLayout().setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddContactActivity.class));
}
});


contactSyncListener = new ContactSyncListener();
DemoHelper.getInstance().addSyncContactListener(contactSyncListener);

blackListSyncListener = new BlackListSyncListener();
DemoHelper.getInstance().addSyncBlackListListener(blackListSyncListener);

contactInfoSyncListener = new ContactInfoSyncListener();
DemoHelper.getInstance().getUserProfileManager().addSyncContactInfoListener(contactInfoSyncListener);

if (DemoHelper.getInstance().isContactsSyncedWithServer()) {
loadingView.setVisibility(View.GONE);
} else if (DemoHelper.getInstance().isSyncingContactsWithServer()) {
loadingView.setVisibility(View.VISIBLE);
}
}

@Override
public void onDestroy() {
super.onDestroy();
if (contactSyncListener != null) {
DemoHelper.getInstance().removeSyncContactListener(contactSyncListener);
contactSyncListener = null;
}

if(blackListSyncListener != null){
DemoHelper.getInstance().removeSyncBlackListListener(blackListSyncListener);
}

if(contactInfoSyncListener != null){
DemoHelper.getInstance().getUserProfileManager().removeSyncContactInfoListener(contactInfoSyncListener);
}
}


protected class HeaderItemClickListener implements OnClickListener{

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.application_item:
// 进入申请与通知页面
startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class));
break;
case R.id.group_item:
// 进入群聊列表页面
startActivity(new Intent(getActivity(), GroupsActivity.class));
break;
case R.id.chat_room_item:
//进入聊天室列表页面
startActivity(new Intent(getActivity(), PublicChatRoomsActivity.class));
break;
case R.id.robot_item:
//进入Robot列表页面
startActivity(new Intent(getActivity(), RobotsActivity.class));
break;

default:
break;
}
}

}


@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
toBeProcessUser = (EaseUser) listView.getItemAtPosition(((AdapterContextMenuInfo) menuInfo).position);
toBeProcessUsername = toBeProcessUser.getUsername();
getActivity().getMenuInflater().inflate(R.menu.em_context_contact_list, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == R.id.delete_contact) {
try {
// delete contact
deleteContact(toBeProcessUser);
// remove invitation message
InviteMessgeDao dao = new InviteMessgeDao(getActivity());
dao.deleteMessage(toBeProcessUser.getUsername());
} catch (Exception e) {
e.printStackTrace();
}
return true;
}else if(item.getItemId() == R.id.add_to_blacklist){
moveToBlacklist(toBeProcessUsername);
return true;
}
return super.onContextItemSelected(item);
}


/**
* delete contact
*
* @param toDeleteUser
*/
public void deleteContact(final EaseUser tobeDeleteUser) {
String st1 = getResources().getString(R.string.deleting);
final String st2 = getResources().getString(R.string.Delete_failed);
final ProgressDialog pd = new ProgressDialog(getActivity());
pd.setMessage(st1);
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new Runnable() {
public void run() {
try {
EMClient.getInstance().contactManager().deleteContact(tobeDeleteUser.getUsername());
// remove user from memory and database
UserDao dao = new UserDao(getActivity());
dao.deleteContact(tobeDeleteUser.getUsername());
DemoHelper.getInstance().getContactList().remove(tobeDeleteUser.getUsername());
getActivity().runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
contactList.remove(tobeDeleteUser);
contactListLayout.refresh();

}
});
} catch (final Exception e) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
Toast.makeText(getActivity(), st2 + e.getMessage(), Toast.LENGTH_LONG).show();
}
});

}

}
}).start();

}

class ContactSyncListener implements DataSyncListener{
@Override
public void onSyncComplete(final boolean success) {
EMLog.d(TAG, "on contact list sync success:" + success);
getActivity().runOnUiThread(new Runnable() {
public void run() {
getActivity().runOnUiThread(new Runnable(){

@Override
public void run() {
if(success){
loadingView.setVisibility(View.GONE);
refresh();
}else{
String s1 = getResources().getString(R.string.get_failed_please_check);
Toast.makeText(getActivity(), s1, Toast.LENGTH_LONG).show();
loadingView.setVisibility(View.GONE);
}
}

});
}
});
}
}

class BlackListSyncListener implements DataSyncListener{

@Override
public void onSyncComplete(boolean success) {
getActivity().runOnUiThread(new Runnable(){

@Override
public void run() {
refresh();
}
});
}

}

class ContactInfoSyncListener implements DataSyncListener{

@Override
public void onSyncComplete(final boolean success) {
EMLog.d(TAG, "on contactinfo list sync success:" + success);
getActivity().runOnUiThread(new Runnable() {

@Override
public void run() {
loadingView.setVisibility(View.GONE);
if(success){
refresh();
}
}
});
}

}

}
界面及初始化

我们先来一个直观的界面感受。
首先是干嘛,是填充了该ListView的头部。

001.jpg

 
@SuppressLint("InflateParams")
@Override
protected void initView() {
super.initView();
@SuppressLint("InflateParams") View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.em_contacts_header, null);
HeaderItemClickListener clickListener = new HeaderItemClickListener();
applicationItem = (ContactItemView) headerView.findViewById(R.id.application_item);
applicationItem.setOnClickListener(clickListener);
headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
headerView.findViewById(R.id.chat_room_item).setOnClickListener(clickListener);
headerView.findViewById(R.id.robot_item).setOnClickListener(clickListener);
listView.addHeaderView(headerView);
//add loading view
loadingView = LayoutInflater.from(getActivity()).inflate(R.layout.em_layout_loading_data, null);
contentContainer.addView(loadingView);

registerForContextMenu(listView);
}
接着我们来看其他方法。

刷新联系人

刷新联系人及邀请信息。
 @SuppressWarnings("unchecked")
@Override
protected void setUpView() {
titleBar.setRightImageResource(R.drawable.em_add);
titleBar.setRightLayoutClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// startActivity(new Intent(getActivity(), AddContactActivity.class));
NetUtils.hasDataConnection(getActivity());
}
});
//设置联系人数据
Map<String, EaseUser> m = DemoHelper.getInstance().getContactList();
if (m instanceof Hashtable<?, ?>) {
m = (Map<String, EaseUser>) ((Hashtable<String, EaseUser>)m).clone();
}
setContactsMap(m);
super.setUpView();
listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EaseUser user = (EaseUser)listView.getItemAtPosition(position);
if (user != null) {
String username = user.getUsername();
// demo中直接进入聊天页面,实际一般是进入用户详情页
startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", username));
}
}
});


// 进入添加好友页
titleBar.getRightLayout().setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddContactActivity.class));
}
});


contactSyncListener = new ContactSyncListener();
DemoHelper.getInstance().addSyncContactListener(contactSyncListener);

blackListSyncListener = new BlackListSyncListener();
DemoHelper.getInstance().addSyncBlackListListener(blackListSyncListener);

contactInfoSyncListener = new ContactInfoSyncListener();
DemoHelper.getInstance().getUserProfileManager().addSyncContactInfoListener(contactInfoSyncListener);

if (DemoHelper.getInstance().isContactsSyncedWithServer()) {
loadingView.setVisibility(View.GONE);
} else if (DemoHelper.getInstance().isSyncingContactsWithServer()) {
loadingView.setVisibility(View.VISIBLE);
}
}
常规的一些界面操作。

注册同步监听

比较有趣的是如下的操作。
contactSyncListener = new ContactSyncListener();
DemoHelper.getInstance().addSyncContactListener(contactSyncListener);

blackListSyncListener = new BlackListSyncListener();
DemoHelper.getInstance().addSyncBlackListListener(blackListSyncListener);

contactInfoSyncListener = new ContactInfoSyncListener();
DemoHelper.getInstance().getUserProfileManager().addSyncContactInfoListener(contactInfoSyncListener);

if (DemoHelper.getInstance().isContactsSyncedWithServer()) {
loadingView.setVisibility(View.GONE);
} else if (DemoHelper.getInstance().isSyncingContactsWithServer()) {
loadingView.setVisibility(View.VISIBLE);
}
添加了三个同步监听。
  • addSyncContactListener 同步联系人监听
  • addSyncBlackListListener 同步黑名单监听
  • addSyncContactInfoListener 同步联系人信息监听
以及判断是否需要同步的
  • isContactsSyncedWithServer
  • isSyncingContactsWithServer


两个方法。

我们再来看其他的方法。

注册同步监听
 
@Override
public void onDestroy() {
super.onDestroy();
if (contactSyncListener != null) {
DemoHelper.getInstance().removeSyncContactListener(contactSyncListener);
contactSyncListener = null;
}

if(blackListSyncListener != null){
DemoHelper.getInstance().removeSyncBlackListListener(blackListSyncListener);
}

if(contactInfoSyncListener != null){
DemoHelper.getInstance().getUserProfileManager().removeSyncContactInfoListener(contactInfoSyncListener);
}
注销四个监听。
 
protected class HeaderItemClickListener implements OnClickListener{

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.application_item:
// 进入申请与通知页面
startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class));
break;
case R.id.group_item:
// 进入群聊列表页面
startActivity(new Intent(getActivity(), GroupsActivity.class));
break;
case R.id.chat_room_item:
//进入聊天室列表页面
startActivity(new Intent(getActivity(), PublicChatRoomsActivity.class));
break;
case R.id.robot_item:
//进入Robot列表页面
startActivity(new Intent(getActivity(), RobotsActivity.class));
break;

default:
break;
}
}
headview四条目监听。

删除联系人及其他监听实现​
/**
* delete contact
*
* @param toDeleteUser
*/
public void deleteContact(final EaseUser tobeDeleteUser) {
String st1 = getResources().getString(R.string.deleting);
final String st2 = getResources().getString(R.string.Delete_failed);
final ProgressDialog pd = new ProgressDialog(getActivity());
pd.setMessage(st1);
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new Runnable() {
public void run() {
try {
EMClient.getInstance().contactManager().deleteContact(tobeDeleteUser.getUsername());
// remove user from memory and database
UserDao dao = new UserDao(getActivity());
dao.deleteContact(tobeDeleteUser.getUsername());
DemoHelper.getInstance().getContactList().remove(tobeDeleteUser.getUsername());
getActivity().runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
contactList.remove(tobeDeleteUser);
contactListLayout.refresh();

}
});
} catch (final Exception e) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
Toast.makeText(getActivity(), st2 + e.getMessage(), Toast.LENGTH_LONG).show();
}
});

}

}
}).start();

}

class ContactSyncListener implements DataSyncListener{
@Override
public void onSyncComplete(final boolean success) {
EMLog.d(TAG, "on contact list sync success:" + success);
getActivity().runOnUiThread(new Runnable() {
public void run() {
getActivity().runOnUiThread(new Runnable(){

@Override
public void run() {
if(success){
loadingView.setVisibility(View.GONE);
refresh();
}else{
String s1 = getResources().getString(R.string.get_failed_please_check);
Toast.makeText(getActivity(), s1, Toast.LENGTH_LONG).show();
loadingView.setVisibility(View.GONE);
}
}

});
}
});
}
}

class BlackListSyncListener implements DataSyncListener{

@Override
public void onSyncComplete(boolean success) {
getActivity().runOnUiThread(new Runnable(){

@Override
public void run() {
refresh();
}
});
}

}

class ContactInfoSyncListener implements DataSyncListener{

@Override
public void onSyncComplete(final boolean success) {
EMLog.d(TAG, "on contactinfo list sync success:" + success);
getActivity().runOnUiThread(new Runnable() {

@Override
public void run() {
loadingView.setVisibility(View.GONE);
if(success){
refresh();
}
}
});
}

}
删除联系人,主要两句话。
 EMClient.getInstance().contactManager().deleteContact
以及
DemoHelper.getInstance().getContactList().remove(tobeDeleteUser.getUsername());
其他监听均实现了DataSyncListener接口。

下面,我们来看他爹。

EaseContactListFragment​
/**
* Copyright (C) 2016 Hyphenate Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hyphenate.easeui.ui;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.EaseContactList;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
* contact list
*
*/
public class EaseContactListFragment extends EaseBaseFragment {
private static final String TAG = "EaseContactListFragment";
protected List<EaseUser> contactList;
protected ListView listView;
protected boolean hidden;
protected ImageButton clearSearch;
protected EditText query;
protected Handler handler = new Handler();
protected EaseUser toBeProcessUser;
protected String toBeProcessUsername;
protected EaseContactList contactListLayout;
protected boolean isConflict;
protected FrameLayout contentContainer;

private Map<String, EaseUser> contactsMap;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.ease_fragment_contact_list, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
//to avoid crash when open app after long time stay in background after user logged into another device
if(savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
return;
super.onActivityCreated(savedInstanceState);
}

@Override
protected void initView() {
contentContainer = (FrameLayout) getView().findViewById(R.id.content_container);

contactListLayout = (EaseContactList) getView().findViewById(R.id.contact_list);
listView = contactListLayout.getListView();

//search
query = (EditText) getView().findViewById(R.id.query);
clearSearch = (ImageButton) getView().findViewById(R.id.search_clear);
}

@Override
protected void setUpView() {
EMClient.getInstance().addConnectionListener(connectionListener);

contactList = new ArrayList<EaseUser>();
getContactList();
//init list
contactListLayout.init(contactList);

if(listItemClickListener != null){
listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EaseUser user = (EaseUser)listView.getItemAtPosition(position);
listItemClickListener.onListItemClicked(user);
}
});
}

query.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
contactListLayout.filter(s);
if (s.length() > 0) {
clearSearch.setVisibility(View.VISIBLE);
} else {
clearSearch.setVisibility(View.INVISIBLE);

}
}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

public void afterTextChanged(Editable s) {
}
});
clearSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
query.getText().clear();
hideSoftKeyboard();
}
});

listView.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard();
return false;
}
});

}


@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
this.hidden = hidden;
if (!hidden) {
refresh();
}
}

@Override
public void onResume() {
super.onResume();
if (!hidden) {
refresh();
}
}


/**
* move user to blacklist
*/
protected void moveToBlacklist(final String username){
final ProgressDialog pd = new ProgressDialog(getActivity());
String st1 = getResources().getString(R.string.Is_moved_into_blacklist);
final String st2 = getResources().getString(R.string.Move_into_blacklist_success);
final String st3 = getResources().getString(R.string.Move_into_blacklist_failure);
pd.setMessage(st1);
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new Runnable() {
public void run() {
try {
//move to blacklist
EMClient.getInstance().contactManager().addUserToBlackList(username,false);
getActivity().runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
Toast.makeText(getActivity(), st2, Toast.LENGTH_SHORT).show();
refresh();
}
});
} catch (HyphenateException e) {
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
Toast.makeText(getActivity(), st3, Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();

}

// refresh ui
public void refresh() {
getContactList();
contactListLayout.refresh();
}


@Override
public void onDestroy() {

EMClient.getInstance().removeConnectionListener(connectionListener);

super.onDestroy();
}


/**
* get contact list and sort, will filter out users in blacklist
*/
protected void getContactList() {
contactList.clear();
if(contactsMap == null){
return;
}
synchronized (this.contactsMap) {
Iterator<Entry<String, EaseUser>> iterator = contactsMap.entrySet().iterator();
List<String> blackList = EMClient.getInstance().contactManager().getBlackListUsernames();
while (iterator.hasNext()) {
Entry<String, EaseUser> entry = iterator.next();
// to make it compatible with data in previous version, you can remove this check if this is new app
if (!entry.getKey().equals("item_new_friends")
&& !entry.getKey().equals("item_groups")
&& !entry.getKey().equals("item_chatroom")
&& !entry.getKey().equals("item_robots")){
if(!blackList.contains(entry.getKey())){
//filter out users in blacklist
EaseUser user = entry.getValue();
EaseCommonUtils.setUserInitialLetter(user);
contactList.add(user);
}
}
}
}

// sorting
Collections.sort(contactList, new Comparator<EaseUser>() {

@Override
public int compare(EaseUser lhs, EaseUser rhs) {
if(lhs.getInitialLetter().equals(rhs.getInitialLetter())){
return lhs.getNick().compareTo(rhs.getNick());
}else{
if("#".equals(lhs.getInitialLetter())){
return 1;
}else if("#".equals(rhs.getInitialLetter())){
return -1;
}
return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
}

}
});

}



protected EMConnectionListener connectionListener = new EMConnectionListener() {

@Override
public void onDisconnected(int error) {
if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE || error == EMError.SERVER_SERVICE_RESTRICTED) {
isConflict = true;
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
onConnectionDisconnected();
}

});
}
}

@Override
public void onConnected() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
onConnectionConnected();
}

});
}
};
private EaseContactListItemClickListener listItemClickListener;


protected void onConnectionDisconnected() {

}

protected void onConnectionConnected() {

}

/**
* set contacts map, key is the hyphenate id
* @param contactsMap
*/
public void setContactsMap(Map<String, EaseUser> contactsMap){
this.contactsMap = contactsMap;
}

public interface EaseContactListItemClickListener {
/**
* on click event for item in contact list
* @param user --the user of item
*/
void onListItemClicked(EaseUser user);
}

/**
* set contact list item click listener
* @param listItemClickListener
*/
public void setContactListItemClickListener(EaseContactListItemClickListener listItemClickListener){
this.listItemClickListener = listItemClickListener;
}

}
填充布局

照例的填充布局

002.jpg


我们看到就一个search。

继续看其他的方法
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.ease_fragment_contact_list, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
//to avoid crash when open app after long time stay in background after user logged into another device
if(savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
return;
super.onActivityCreated(savedInstanceState);
}

@Override
protected void initView() {
contentContainer = (FrameLayout) getView().findViewById(R.id.content_container);

contactListLayout = (EaseContactList) getView().findViewById(R.id.contact_list);
listView = contactListLayout.getListView();

//search
query = (EditText) getView().findViewById(R.id.query);
clearSearch = (ImageButton) getView().findViewById(R.id.search_clear);
}
照例的填充,冲突标志位,初始化view。

初始化view​
@Override
protected void setUpView() {
EMClient.getInstance().addConnectionListener(connectionListener);

contactList = new ArrayList<EaseUser>();
getContactList();
//init list
contactListLayout.init(contactList);

if(listItemClickListener != null){
listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EaseUser user = (EaseUser)listView.getItemAtPosition(position);
listItemClickListener.onListItemClicked(user);
}
});
}

query.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
contactListLayout.filter(s);
if (s.length() > 0) {
clearSearch.setVisibility(View.VISIBLE);
} else {
clearSearch.setVisibility(View.INVISIBLE);

}
}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

public void afterTextChanged(Editable s) {
}
});
clearSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
query.getText().clear();
hideSoftKeyboard();
}
});

listView.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard();
return false;
}
});

}
寻常的初始化。

拉黑及刷新​
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
this.hidden = hidden;
if (!hidden) {
refresh();
}
}

@Override
public void onResume() {
super.onResume();
if (!hidden) {
refresh();
}
}


/**
* move user to blacklist
*/
protected void moveToBlacklist(final String username){
final ProgressDialog pd = new ProgressDialog(getActivity());
String st1 = getResources().getString(R.string.Is_moved_into_blacklist);
final String st2 = getResources().getString(R.string.Move_into_blacklist_success);
final String st3 = getResources().getString(R.string.Move_into_blacklist_failure);
pd.setMessage(st1);
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new Runnable() {
public void run() {
try {
//move to blacklist
EMClient.getInstance().contactManager().addUserToBlackList(username,false);
getActivity().runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
Toast.makeText(getActivity(), st2, Toast.LENGTH_SHORT).show();
refresh();
}
});
} catch (HyphenateException e) {
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
Toast.makeText(getActivity(), st3, Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();

}

// refresh ui
public void refresh() {
getContactList();
contactListLayout.refresh();
}


@Override
public void onDestroy() {

EMClient.getInstance().removeConnectionListener(connectionListener);

super.onDestroy();
}
拉黑,以及刷新。

联系人排序​
/**
* get contact list and sort, will filter out users in blacklist
*/
protected void getContactList() {
contactList.clear();
if(contactsMap == null){
return;
}
synchronized (this.contactsMap) {
Iterator<Entry<String, EaseUser>> iterator = contactsMap.entrySet().iterator();
List<String> blackList = EMClient.getInstance().contactManager().getBlackListUsernames();
while (iterator.hasNext()) {
Entry<String, EaseUser> entry = iterator.next();
// to make it compatible with data in previous version, you can remove this check if this is new app
if (!entry.getKey().equals("item_new_friends")
&& !entry.getKey().equals("item_groups")
&& !entry.getKey().equals("item_chatroom")
&& !entry.getKey().equals("item_robots")){
if(!blackList.contains(entry.getKey())){
//filter out users in blacklist
EaseUser user = entry.getValue();
EaseCommonUtils.setUserInitialLetter(user);
contactList.add(user);
}
}
}
}

// sorting
Collections.sort(contactList, new Comparator<EaseUser>() {

@Override
public int compare(EaseUser lhs, EaseUser rhs) {
if(lhs.getInitialLetter().equals(rhs.getInitialLetter())){
return lhs.getNick().compareTo(rhs.getNick());
}else{
if("#".equals(lhs.getInitialLetter())){
return 1;
}else if("#".equals(rhs.getInitialLetter())){
return -1;
}
return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
}

}
});

}
联系人的排序,将会过滤掉黑名单人员。

各种点击监听​
protected EMConnectionListener connectionListener = new EMConnectionListener() {

@Override
public void onDisconnected(int error) {
if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE || error == EMError.SERVER_SERVICE_RESTRICTED) {
isConflict = true;
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
onConnectionDisconnected();
}

});
}
}

@Override
public void onConnected() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
onConnectionConnected();
}

});
}
};
private EaseContactListItemClickListener listItemClickListener;


protected void onConnectionDisconnected() {

}

protected void onConnectionConnected() {

}

/**
* set contacts map, key is the hyphenate id
* @param contactsMap
*/
public void setContactsMap(Map<String, EaseUser> contactsMap){
this.contactsMap = contactsMap;
}

public interface EaseContactListItemClickListener {
/**
* on click event for item in contact list
* @param user --the user of item
*/
void onListItemClicked(EaseUser user);
}

/**
* set contact list item click listener
* @param listItemClickListener
*/
public void setContactListItemClickListener(EaseContactListItemClickListener listItemClickListener){
this.listItemClickListener = listItemClickListener;
}
正常的点击事件。

他爷爷是EaseBaseFragment之前分析过就不分析了。

0 个评论

要回复文章请先登录注册