环信官方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 m = DemoHelper.getInstance().getContactList();        if (m instanceof Hashtable) {            //noinspection unchecked            m = (Map) ((Hashtable)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 m = DemoHelper.getInstance().getContactList();        if (m instanceof Hashtable) {            m = (Map) ((Hashtable)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的头部。

@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 m = DemoHelper.getInstance().getContactList();

if (m instanceof Hashtable) {

m = (Map) ((Hashtable)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 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 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();        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> iterator = contactsMap.entrySet().iterator();            List blackList = EMClient.getInstance().contactManager().getBlackListUsernames();            while (iterator.hasNext()) {                Entry 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() {​            @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 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;    }    }

填充布局

照例的填充布局

我们看到就一个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();

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> iterator = contactsMap.entrySet().iterator();

List blackList = EMClient.getInstance().contactManager().getBlackListUsernames();

while (iterator.hasNext()) {

Entry 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() {

@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 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之前分析过就不分析了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,948评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,371评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,490评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,521评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,627评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,842评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,997评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,741评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,203评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,534评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,673评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,339评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,955评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,770评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,000评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,394评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,562评论 2 349

推荐阅读更多精彩内容