Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 ExpandableListView 打造微信風格通訊錄:分組、默認展開與自定義分割線

編輯:關於 Android 開發

此前寫過一篇簡單介紹 ExpandableListView 好友分組的文章,這次把它放進仿微信 APP 的完整場景裡,重點解決幾個實戰問題:首屏全部展開、禁止收縮、去掉多餘的組名、以及替換系統分割線。

一、基本思路

  1. 先準備數據源,再給 ExpandableListView 設置適配器。
  2. 數據源即自定義的 ExpandableAdapter,繼承 BaseExpandableListAdapter,重寫其中的各個方法;組與子項的樣式通過 getGroupView() 與 getChildView() 加載自定義布局。
  3. 調用 setAdapter() 即可完成收縮展開的基本功能。

二、微信風格需要額外處理的四件事

(1)首次加載默認全部展開

設置完適配器後,遍歷組序號逐一展開:

// Group.size() 為組個數;若用數組存儲則取 group.length
for (int i = 0; i < Group.size(); i++) {
    expandableListView.expandGroup(i);
}

記得在展開前判斷 adapter 是否為空、有沒有 group 數據,避免空指針。

(2)保持始終展開、無法收縮

expandableListView.setOnGroupClickListener(new OnGroupClickListener() {
    @Override
    public boolean onGroupClick(ExpandableListView parent, View v,
                                int groupPosition, long id) {
        return true;   // 返回 true 攔截點擊,組項無法收縮
    }
});

(3)取消通訊錄上方的組名

微信裡「新的朋友」「群聊」「標簽」「公眾號」是直接貼著頂部導航的,沒有組標題。做法是把它們做成一個整體布局,塞進列表的首位。

(4)替換分割線

在 item 布局裡自繪一條左右留白的 View,同時把 ExpandableListView 自帶的 divider 置為透明。

三、布局實現

contact_fragment.xml:整體布局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/fragmentback">

    <ExpandableListView
        android:id="@+id/contact_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider ="#FFFFFF"/>   <!-- 用白色遮掉系統分割線 -->
</LinearLayout>

contact_list_group_item.xml:組名布局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/fragmentback">

    <TextView
        android:id="@+id/group_tv"
        android:textSize="20sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:gravity="center_vertical"/>
</LinearLayout>

contact_list_item.xml:子項布局(含自定義分割線)

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:background="@color/colorwhite"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:paddingLeft="10dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:gravity="center_vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/contact_item_iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/default_fmessage"
                android:adjustViewBounds="true"
                android:maxWidth="35dp"/>

            <TextView
                android:id="@+id/contact_item_tv"
                android:layout_margin="10dp"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="新的朋友"/>
        </LinearLayout>

        <View   <!-- 左右各留 10dp 的自定義分割線 -->
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@color/fragmentback"/>
    </LinearLayout>
</LinearLayout>

contact_list_title.xml:頂部功能入口(不需要組名)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:background="@color/colorwhite"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- 新的朋友 -->
        <LinearLayout
            android:paddingLeft="10dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:gravity="center_vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/default_fmessage"
                android:adjustViewBounds="true"
                android:maxWidth="35dp"/>
            <TextView
                android:layout_margin="10dp"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="新的朋友"/>
        </LinearLayout>
        <View android:layout_width="match_parent" android:layout_height="1dp"
            android:layout_marginLeft="10dp" android:layout_marginRight="10dp"
            android:background="@color/fragmentback"/>

        <!-- 群聊 -->
        <LinearLayout ... >
            <ImageView android:src="@mipmap/default_chatroom" ... />
            <TextView android:text="群聊" ... />
        </LinearLayout>
        <View ... />

        <!-- 標簽 -->
        <LinearLayout ... >
            <ImageView android:src="@mipmap/default_contactlabel" ... />
            <TextView android:text="標簽" ... />
        </LinearLayout>
        <View ... />

        <!-- 公眾號 -->
        <LinearLayout ... >
            <ImageView android:src="@mipmap/default_servicebrand_contact" ... />
            <TextView android:text="公眾號" ... />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

四、自定義適配器

核心技巧是:把「頂部入口」當成第 0 組,在 getGroupView() 和 getChildView() 裡判斷 groupPosition == 0,命中時加載 contact_list_title,否則走常規的組名/子項布局。

public class MyExpandableListAdapter extends BaseExpandableListAdapter {
    Context context;
    String[] group;
    String[][] itemName;
    int[][] itemIcon;

    public MyExpandableListAdapter(Context context, String[] group,
                                   String[][] itemName, int[][] itemIcon) {
        this.context = context;
        this.group = group;
        this.itemName = itemName;
        this.itemIcon = itemIcon;
    }

    @Override public int getGroupCount() { return group.length; }
    @Override public int getChildrenCount(int groupPosition) {
        return itemName[groupPosition].length;
    }
    @Override public Object getGroup(int groupPosition) { return group[groupPosition]; }
    @Override public Object getChild(int groupPosition, int childPosition) {
        return itemName[groupPosition][childPosition];
    }
    @Override public long getGroupId(int groupPosition) { return groupPosition; }
    @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; }
    @Override public boolean hasStableIds() { return false; }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (groupPosition == 0) {
            // 第一組不顯示組名,改用頂部入口布局
            convertView = LayoutInflater.from(context)
                    .inflate(R.layout.contact_list_title, null);
        } else {
            if (convertView == null) {
                convertView = LayoutInflater.from(context)
                        .inflate(R.layout.contact_list_group_item, null);
                vh = new ViewHolder();
                vh.tv = (TextView) convertView.findViewById(R.id.group_tv);
                convertView.setTag(vh);
            }
            vh = (ViewHolder) convertView.getTag();
            vh.tv.setText(group[groupPosition]);
        }
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (groupPosition == 0) {
            convertView = LayoutInflater.from(context)
                    .inflate(R.layout.contact_list_title, null);
        } else {
            if (convertView == null) {
                convertView = LayoutInflater.from(context)
                        .inflate(R.layout.contact_list_item, null);
                vh = new ViewHolder();
                vh.tv = (TextView) convertView.findViewById(R.id.contact_item_tv);
                vh.iv = (ImageView) convertView.findViewById(R.id.contact_item_iv);
                convertView.setTag(vh);
            }
            vh = (ViewHolder) convertView.getTag();
            vh.tv.setText(itemName[groupPosition][childPosition]);
            vh.iv.setImageResource(itemIcon[groupPosition][childPosition]);
        }
        return convertView;
    }

    @Override public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    class ViewHolder {
        TextView tv;
        ImageView iv;
    }
}

五、Fragment 中使用

注意 group 數組首位放空串、itemName 與 itemIcon 首位放空數組,與適配器裡的「第 0 組是頂部入口」約定相對應。

public class ContactFragment extends Fragment {
    private ExpandableListView contact_list;

    String[] group = {"", "好友列表"};
    String[][] itemName = {{},
        {"郭嘉", "黃月英", "華佗", "劉備", "陸遜", "呂布", "呂蒙", "馬超",
         "司馬懿", "孫權", "孫尚香", "夏侯惇", "許褚", "楊修", "張飛",
         "趙雲", "甄姬", "周瑜", "諸葛亮"}};
    int[][] itemIcon = {{},
        {R.mipmap.guojia, R.mipmap.huangyueying, R.mipmap.huatuo, R.mipmap.liubei,
         R.mipmap.luxun, R.mipmap.lvbu, R.mipmap.lvmeng, R.mipmap.machao,
         R.mipmap.simayi, R.mipmap.sunquan, R.mipmap.sunshangxiang, R.mipmap.xiahoudun,
         R.mipmap.xuchu, R.mipmap.yangxiu, R.mipmap.zhangfei, R.mipmap.zhaoyun,
         R.mipmap.zhenji, R.mipmap.zhouyu, R.mipmap.zhugeliang}};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.contact_fragment, container, false);
        contact_list = (ExpandableListView) view.findViewById(R.id.contact_list);

        MyExpandableListAdapter adapter =
                new MyExpandableListAdapter(getContext(), group, itemName, itemIcon);
        contact_list.setAdapter(adapter);

        contact_list.setGroupIndicator(null);   // 去掉默認箭頭

        for (int i = 0; i < group.length; i++) {
            contact_list.expandGroup(i);        // 默認全部展開
        }

        contact_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                return true;                    // 禁止收縮
            }
        });
        return view;
    }
}

六、小結

實現方式不止一種,把頂部入口做成 headerView 或干脆改用 RecyclerView 配合多種 ItemType,代碼會更清晰、性能也更好。ExpandableListView 的價值在於 API 簡單、上手快,適合分組結構固定且層級不深的場景;一旦需要復雜的異步加載、局部刷新或混排布局,還是建議遷移到 RecyclerView。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved