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

用 ExpandableListView 打造微信風格的通訊錄界面

編輯:關於 Android 程式設計

微信的通訊錄有個很有意思的設計:頂部「新的朋友、群聊、標籤、公眾號」是固定的一塊,下方好友名單則按字母分組、預設全展開且點標題不會收合。用 ExpandableListView 完全可以做到,只是需要幾個小技巧。

基本三步驟

  1. 準備資料源:自訂一個繼承 BaseExpandableListAdapter 的 Adapter,在其中定義組與子項的資料。
  2. 定義布局:透過 getGroupView() 與 getChildView() 指定組標題與子項的外觀。
  3. 掛上適配器:ExpandableListView.setAdapter() 即可獲得收合能力。

要做出微信的樣子,還得額外處理四件事:

  • 首次載入時預設全部展開。
  • 讓組標題點擊後無法收合。
  • 把頂部那四個入口做成一個獨立布局,不佔用組標題的位置。
  • 自訂分隔線。

一、通訊錄整體布局

先把 ExpandableListView 自帶的分隔線關掉,改由 item 自己畫:

<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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:gravity="center_vertical"
        android:textSize="20sp" />
</LinearLayout>

三、子項布局(contact_list_item.xml)

分隔線直接在 item 內部用一條 View 畫出來,這樣左側就能留出與微信一致的縮排:

<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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorwhite"
        android:orientation="vertical">

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

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

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

        <View
            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)

觀察微信可以發現,「新的朋友/群聊/標籤/公眾號」上方直接就是導航列,沒有任何組標題。做法是把這四項寫成一個獨立布局,之後在 Adapter 中判定「第 0 組」時載入它:

<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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorwhite"
        android:orientation="vertical">

        <!-- 新的朋友 -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:gravity="center_vertical"
            android:orientation="horizontal">

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

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_margin="10dp"
                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>
</LinearLayout>

五、自訂 Adapter

兩個關鍵技巧都在這裡:第 0 組改用 title 布局、其餘組才用 group 布局;子項也做同樣判斷。

public class MyExpandableListAdapter extends BaseExpandableListAdapter {

    private final Context context;
    private final String[] group;
    private final String[][] itemName;
    private final 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) {
        // 第 0 組沒有組標題,改用固定入口布局
        if (groupPosition == 0) {
            return LayoutInflater.from(context)
                    .inflate(R.layout.contact_list_title, null);
        }

        ViewHolder vh;
        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);
        } else {
            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) {
        if (groupPosition == 0) {
            return LayoutInflater.from(context)
                    .inflate(R.layout.contact_list_title, null);
        }

        ViewHolder vh;
        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);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        vh.tv.setText(itemName[groupPosition][childPosition]);
        vh.iv.setImageResource(itemIcon[groupPosition][childPosition]);
        return convertView;
    }

    @Override public boolean isChildSelectable(int g, int c) { return true; }

    class ViewHolder {
        TextView tv;
        ImageView iv;
    }
}

六、Fragment 端的設定

public class ContactFragment extends Fragment {

    private ExpandableListView contact_list;

    // 第 0 組的標題與資料刻意留空,因為它用的是固定入口布局
    String[] group = {"", "好友列表"};
    String[][] itemName = {{}, {"郭嘉", "黃月英", "華佗", "劉備", "陸遜"}};
    int[][] itemIcon = {{}, {R.mipmap.guojia, R.mipmap.huangyueying,
            R.mipmap.huatuo, R.mipmap.liubei, R.mipmap.luxun}};

    @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);

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

        contact_list.setGroupIndicator(null);   // 拿掉預設箭頭

        // 預設全部展開(記得先確認 adapter 不為 null 且有資料)
        for (int i = 0; i < group.length; i++) {
            contact_list.expandGroup(i);
        }

        // 回傳 true 表示攔下事件,組標題點了不會收合
        contact_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                return true;
            }
        });

        return view;
    }
}

幾個關鍵技巧整理

預設展開:setAdapter() 之後迴圈呼叫 expandGroup(i)。注意如果資料是異步取得的,這段必須放在資料回來之後執行,否則展開狀態會失效。

禁止收合:setOnGroupClickListener 回傳 true 就代表事件已被消費,收合動作不會發生。

去掉預設箭頭:setGroupIndicator(null)。若使用 XML,則是 android:groupIndicator="@null"。

最後補一句實務建議:ExpandableListView 是相當早期的元件,在複雜列表、混排不同樣式、或需要自訂動畫的情況下會漸漸力不從心。若你的專案還在評估階段,直接用 RecyclerView 搭配多種 ItemViewType 會更好維護——本文的「第 0 組換布局」技巧,在 RecyclerView 裡就只是 getItemViewType() 的一個分支而已。

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