Android之BaseExpandableListAdapter使用心得(QQ續一)

來源:互聯網
上載者:User

        前段時間跟大家分享了ExpandableListView的使用,不知道的童鞋,可以去這裡看一下:http://blog.csdn.net/weidi1989/article/details/7995552
        但是我最近做那個QQ項目是遇到一個問題,如果給這個ExpandableListView添加動態從網上擷取的資料呢?前面跟大家分享的時候,是用了靜態資料,很好處理。大組跟小組就類似於一個一維數組和二維數組,但我們從伺服器擷取的資料可能並不是這樣!比如我做的這個QQ從伺服器擷取的就是一個List<User>,這麼一個使用者數組,那些分組資訊都包含在每個使用者之中,像這樣的資料又該如何添加到適配器裡面呢?好了,下面跟大家分享一下我的處理辦法。先看一張,有圖有真相,哈哈:

 

下面是對應好友在資料庫中的分組,自己本人預設為在第一組。QQ好像也是這麼處理的


先看一下我們自訂的適配器代碼,看看需要什麼樣的資料,然後根據需求,傳遞對應的資料。

/** * 自訂ExpandableListView的適配器 *  * @author way *  */public class MyExAdapter extends BaseExpandableListAdapter {private int[] imgs = { R.drawable.icon, R.drawable.f1, R.drawable.f2,R.drawable.f3, R.drawable.f4, R.drawable.f5, R.drawable.f6,R.drawable.f7, R.drawable.f8, R.drawable.f9 };// 頭像資源數組private Context context;private List<GroupFriend> group;// 傳遞過來的經過處理的總資料public MyExAdapter(Context context, List<GroupFriend> group) {super();this.context = context;this.group = group;}// 得到大群組成員的viewpublic View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {if (convertView == null) {LayoutInflater inflater = LayoutInflater.from(context);convertView = inflater.inflate(R.layout.member_listview, null);}TextView title = (TextView) convertView.findViewById(R.id.content_001);title.setText(getGroup(groupPosition).toString());// 設定大群組成員名稱ImageView image = (ImageView) convertView.findViewById(R.id.tubiao);// 是否展開大組的箭頭表徵圖if (isExpanded)// 大組展開時的箭頭表徵圖image.setBackgroundResource(R.drawable.group_unfold_arrow);else// 大組合并時的箭頭表徵圖image.setBackgroundResource(R.drawable.group_fold_arrow);return convertView;}// 得到大群組成員的idpublic long getGroupId(int groupPosition) {return groupPosition;}// 得到大群組成員名稱public Object getGroup(int groupPosition) {return group.get(groupPosition).getGroupName();}// 得到大群組成員總數public int getGroupCount() {return group.size();}// 得到小組成員的viewpublic View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {if (convertView == null) {LayoutInflater inflater = LayoutInflater.from(context);convertView = inflater.inflate(R.layout.item, null);}final TextView title = (TextView) convertView.findViewById(R.id.name_item);// 顯示使用者名稱final TextView title2 = (TextView) convertView.findViewById(R.id.id_item);// 顯示使用者idImageView icon = (ImageView) convertView.findViewById(R.id.imageView_item);// 顯示帳戶圖片,其實還可以判斷是否線上,選擇黑白和彩色頭像,我這裡未處理,沒資源,呵呵final String name = group.get(groupPosition).getChild(childPosition).getName();final String id = group.get(groupPosition).getChild(childPosition).getId()+ "";final int img = group.get(groupPosition).getChild(childPosition).getImg();title.setText(name);// 大標題title2.setText(id);// 小標題icon.setImageResource(imgs[img]);convertView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 下面是添加到最近會話列表處理RecentChatEntity entity = new RecentChatEntity(img, 0, name,MyDate.getDateEN(), "");FriendListActivity.mRecentList.add(entity);FriendListActivity.mRecentAdapter = new RecentChatAdapter(context, FriendListActivity.mRecentList);FriendListActivity.mRecentListView.setAdapter(FriendListActivity.mRecentAdapter);// 下面是切換到聊天介面處理User u = new User();u.setName(name);u.setId(Integer.parseInt(id));u.setImg(img);Intent intent = new Intent(context, ChatActivity.class);intent.putExtra("user", u);context.startActivity(intent);// Toast.makeText(Tab2.this, "開始聊天", 0).show();}});return convertView;}// 得到小組成員idpublic long getChildId(int groupPosition, int childPosition) {return childPosition;}// 得到小組成員的名稱public Object getChild(int groupPosition, int childPosition) {return group.get(groupPosition).getChild(childPosition);}// 得到小組成員的數量public int getChildrenCount(int groupPosition) {return group.get(groupPosition).getChildSize();}/** * Indicates whether the child and group IDs are stable across changes to * the underlying data. 表明大組和小組id是否穩定的更改底層資料。 *  * @return whether or not the same ID always refers to the same object * @see Adapter#hasStableIds() */public boolean hasStableIds() {return true;}// 得到小組成員是否被選擇public boolean isChildSelectable(int groupPosition, int childPosition) {return true;}/** * 這個方法是我自訂的,用於下拉重新整理好友的方法 *  * @param group *            傳遞進來的新資料 */public void updata(List<GroupFriend> group) {this.group = null;this.group = group;}}

從自訂配接器可以看出,需要一個List<GroupFriend>,這實際上也是我自訂的一個對象GroupFriend數組,為了方便處理,我把大群組成員以及每個大組對應的小組成員都封裝到GroupFriend這個對象中,下面我們來看一下GroupFriend的這個對象代碼:

/** * 自訂的GroupFriend對象,用來封裝大組名稱和分配對應的資料 *  * @author way *  */public class GroupFriend {private String groupName;// 大組名稱private List<User> groupChild;// 對應大組的小組成員對象數組public GroupFriend() {super();}public GroupFriend(String groupName, List<User> groupChild) {super();this.groupName = groupName;this.groupChild = groupChild;}public void add(User u) {// 往小組中添加使用者groupChild.add(u);}public void remove(User u) {// 根據使用者物件移除使用者groupChild.remove(u);}public void remove(int index) {// 根據下標移除使用者groupChild.remove(index);}public int getChildSize() {// 小組的大小return groupChild.size();}public User getChild(int index) {// 根據下標得到使用者return groupChild.get(index);}// get...set...public String getGroupName() {return groupName;}public void setGroupName(String groupName) {this.groupName = groupName;}public List<User> getGroupChild() {return groupChild;}public void setGroupChild(List<User> groupChild) {this.groupChild = groupChild;}}

好了,適配都根據我們的需求整完了,下面我們就處理一下伺服器傳遞過來的List<User>對象(代碼出自我的QQ項目中,我這裡只截取其中重要的一部分):

         private List<GroupFriend> group;//需要傳遞給適配器的資料private String[] groupName = { "我的好友", "我的同學", "家長控制" };// 大群組成員名          /** * 處理伺服器傳遞過來的使用者數組資料, *  * @param list *            從伺服器擷取的使用者數組 */private void initListViewData(List<User> list) {group = new ArrayList<GroupFriend>();// 執行個體化for (int i = 0; i < groupName.length; ++i) {// 根據大組的數量,迴圈給各大組分配成員List<User> child = new ArrayList<User>();// 裝小組成員的listGroupFriend groupInfo = new GroupFriend(groupName[i], child);// 我們自訂的大群組成員對象for (User u : list) {if (u.getGroup() == i)// 判斷一下是屬於哪個大組child.add(u);}group.add(groupInfo);// 把自訂大群組成員對象放入一個list中,傳遞給適配器}}

經過這個資料加工廠後產生的List<GroupFriend>,我們就可以用來執行個體化配接器物件了:

                 // 下面是處理好友名單介面處理myListView = (MyListView) lay2.findViewById(R.id.tab2_listView);//擷取我們自訂的可以下拉重新整理的ListView對象myExAdapter = new MyExAdapter(this, group);//執行個體化適配器myListView.setAdapter(myExAdapter);//為我們自訂的ListView設定適配器myListView.setGroupIndicator(null);// 不設定大組指標表徵圖,因為我們自訂設定了myListView.setDivider(null);// 設定圖片可展開的myListView.setFocusable(true);// 聚焦才可以下拉重新整理myListView.setonRefreshListener(new MyRefreshListener());//監聽下拉重新整理狀態

OK,大功告成,應該處理資料還有很多其他的辦法,這隻是我個人的一點思路而已,僅供參考,謝謝大家。

由於上面提到了我們自訂下拉重新整理的ListView,下面順便貼出,下拉重新整理後的處理代碼:

/** * 好友名單下拉重新整理監聽與實現,非同步任務 *  * @author way *  */public class MyRefreshListener implements MyListView.OnRefreshListener {@Overridepublic void onRefresh() {new AsyncTask<Void, Void, Void>() {List<User> list;protected Void doInBackground(Void... params) {// 從伺服器重新擷取好友名單if (GetMsgService.isStart) {ClientOutputThread out = GetMsgService.client.getClientOutputThread();TranObject o = new TranObject(TranObjectType.REFRESH);o.setFromUser(Integer.parseInt(util.getId()));out.setMsg(o);// 為了及時收到伺服器發過來的訊息,我這裡直接通過監聽收訊息線程,擷取好友名單,就不通過接收廣播了ClientInputThread in = GetMsgService.client.getClientInputThread();in.setMessageListener(new MessageListener() {@Overridepublic void Message(TranObject msg) {// TODO Auto-generated method stubif (msg != null&& msg.getType() == TranObjectType.REFRESH) {list = (List<User>) msg.getObject();//擷取到的資料if (list.size() > 0) {// System.out.println("Friend:" + list);initListViewData(list);//交給寫好的方法加工一下myExAdapter.updata(group);//調用自訂更新的方法userDB.updateUser(list);// 儲存到資料庫}}}});}return null;}@Overrideprotected void onPostExecute(Void result) {myExAdapter.notifyDataSetChanged();//通知更新了myListView.onRefreshComplete();//下拉重新整理結束Toast.makeText(FriendListActivity.this, "重新整理成功", 0).show();}}.execute(null);}}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.