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

Android 可折疊清單實作:用 ExpandableListView 打造類 QQ 好友分組列表

編輯:關於 Android 程式設計

一、先看概念

ExpandableListView 顧名思義就是「可以展開的清單」。它的外觀是兩層結構:第一層是可點擊的分組項,點下去之後,該分組下方會展開第二層的子項列表。原理與普通 ListView 幾乎一致,只不過它把「一份資料源 + 一個 Adapter」變成了「兩份資料源 + 一個 Adapter」。

普通 ListView 的 BaseAdapter 需要覆寫 4 個方法:

@Override
public int getCount() {
    return 0;
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    return null;
}

而 BaseExpandableListAdapter 則需要覆寫 10 個方法:

@Override
public int getGroupCount() {
    return 0;
}

@Override
public int getChildrenCount(int i) {
    return 0;
}

@Override
public Object getGroup(int i) {
    return null;
}

@Override
public Object getChild(int i, int i1) {
    return null;
}

@Override
public long getGroupId(int i) {
    return 0;
}

@Override
public long getChildId(int i, int i1) {
    return 0;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
    return null;
}

@Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
    return null;
}

@Override
public boolean isChildSelectable(int i, int i1) {
    return false;
}

仔細對照就會發現,多數方法與 ListView 一一對應,真正新增的只有兩個:

hasStableIds():宣告分組視圖與子視圖的 ID 是否能在後端資料變動後仍然穩定指向同一個物件。回傳 true 表示相同的 ID 永遠對應同一筆資料。

isChildSelectable(groupPosition, childPosition):決定指定位置上的子項能不能被點選。參數 groupPosition 是子項所屬分組的位置,childPosition 是子項在該分組內的位置。

二、常用 XML 屬性

// 各組內子項之間的分隔線
android:childDivider

// 顯示在子項旁的 Drawable,可以是圖片
android:childIndicator

// 子項指示圖示的左側起點(從左端 0 開始計算,例如設為 3dip 則從左起 3dip 處繪製)
android:childIndicatorLeft

// 子項指示圖示的右側終點
android:childIndicatorRight

// 顯示在分組項旁的 Drawable,可以是圖片
android:groupIndicator

// 分組指示圖示的左側起點
android:indicatorLeft

// 分組指示圖示的右側終點
android:indicatorRight

去掉系統預設箭頭

使用 ExpandableListView 時,即使自訂了佈局,左側仍會出現一個系統自帶的箭頭圖示。只要一行程式碼就能拿掉:

settingLists.setGroupIndicator(null);

三、Demo 完整實作

1. 主佈局

只需要一個控件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    tools:context="com.duanlian.expendablelistviewdemo.MainActivity"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools">

    <ExpandableListView
        android:id="@+id/expendablelistview"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    </ExpandableListView>

</RelativeLayout>

2. Activity 程式碼

寫法與 ListView 相同:準備一個 Adapter、兩份資料源,然後綁定。

package com.duanlian.expendablelistviewdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ExpandableListView;

import com.duanlian.expendablelistviewdemo.adapter.MyAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ExpandableListView expandableListView;
    private MyAdapter myAdapter;
    private List<String> groupList;
    private List<List<String>> childList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        expandableListView = (ExpandableListView) findViewById(R.id.expendablelistview);
        groupList = new ArrayList<>();
        childList = new ArrayList<>();

        addData("幼稚園同學", new String[]{"小明", "小華", "阿哲", "小丸子", "大雄"});
        addData("小學同學", new String[]{"小新", "靜香", "胖虎", "小夫", "阿福"});
        addData("高中同學", new String[]{"小滿", "阿德", "小綠", "大文", "阿寶"});
        addData("大學同學", new String[]{"小雲", "阿明", "小晴", "大偉", "小柔"});
        addData("研究所同學", new String[]{"小唐", "阿凱", "小玫", "大川", "小悅"});
        addData("同事夥伴", new String[]{"小陳", "阿宏", "小綠", "大維", "小珊"});
        addData("社團好友", new String[]{"小胖", "阿龍", "小琪", "大倫", "小安"});

        myAdapter = new MyAdapter(this, groupList, childList);
        expandableListView.setAdapter(myAdapter);
    }

    /**
     * 加入一組資料:group 為分組名稱,friend 為該組底下的成員
     */
    private void addData(String group, String[] friend) {
        groupList.add(group);
        // 每一個分組展開後,各自對應一個獨立的子清單
        List<String> childItem = new ArrayList<>();
        for (int i = 0; i < friend.length; i++) {
            childItem.add(friend[i]);
        }
        childList.add(childItem);
    }
}

3. 兩份 item 佈局

外層(分組項):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:background="#ed88ed"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <TextView
        android:gravity="center_vertical"
        android:id="@+id/group_textview"
        android:layout_height="50dp"
        android:layout_marginLeft="40dp"
        android:layout_width="wrap_content"
        android:text="我的好友"
        android:textSize="20sp" />

    <TextView
        android:gravity="center_vertical"
        android:id="@+id/group_number"
        android:layout_alignParentRight="true"
        android:layout_height="50dp"
        android:layout_marginRight="20dp"
        android:layout_width="wrap_content"
        android:text="20"
        android:textSize="15sp" />

</RelativeLayout>

內層(子項):

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

    <com.duanlian.expendablelistviewdemo.CircleImageView
        android:id="@+id/child_img"
        android:layout_centerVertical="true"
        android:layout_height="30dp"
        android:layout_marginLeft="10dp"
        android:layout_width="30dp"
        android:src="@mipmap/duanlian" />

    <TextView
        android:gravity="center_vertical"
        android:id="@+id/child_name"
        android:layout_height="40dp"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@+id/child_img"
        android:layout_width="wrap_content"
        android:text="好友暱稱"
        android:textSize="16sp" />

    <TextView
        android:gravity="center_vertical"
        android:id="@+id/child_model"
        android:layout_alignParentRight="true"
        android:layout_height="40dp"
        android:layout_marginRight="5dp"
        android:layout_width="wrap_content"
        android:text="4G"
        android:textSize="13sp" />

</RelativeLayout>

其中的圓形頭像屬於自訂 View,此處不再重複說明。

4. 核心:Adapter

和 ListView 一樣,可以選 SimpleAdapter、ArrayAdapter 或 BaseAdapter,這裡採用 BaseAdapter 的思路,讓 Adapter 繼承 BaseExpandableListAdapter:

package com.duanlian.expendablelistviewdemo.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import com.duanlian.expendablelistviewdemo.R;

import java.util.List;

public class MyAdapter extends BaseExpandableListAdapter {

    private List<String> groupList;             // 外層資料源
    private List<List<String>> childList;       // 內層資料源
    private Context context;

    public MyAdapter(Context context, List<String> groupList, List<List<String>> childList) {
        this.context = context;
        this.groupList = groupList;
        this.childList = childList;
    }

    @Override
    public int getGroupCount() {
        return groupList.size();
    }

    /**
     * 必須回傳對應分組底下子清單的 size
     */
    @Override
    public int getChildrenCount(int groupPosition) {
        return childList.get(groupPosition).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return groupPosition;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return childList.get(groupPosition).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        convertView = View.inflate(context, R.layout.item_group, null);
        // 分組名稱
        TextView textView = (TextView) convertView.findViewById(R.id.group_textview);
        // 子項數量
        TextView number = (TextView) convertView.findViewById(R.id.group_number);
        number.setText(childList.get(groupPosition).size() + "個");
        textView.setText(groupList.get(groupPosition));
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup viewGroup) {
        view = View.inflate(context, R.layout.item_child, null);
        TextView textView = (TextView) view.findViewById(R.id.child_name);
        textView.setText(childList.get(groupPosition).get(childPosition));
        return view;
    }

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

四、小結

整體流程與 ListView 幾乎一致,差別只在於「多一層資料、多幾個方法」。掌握 getGroupCount / getChildrenCount / getGroupView / getChildView 這四個關鍵方法,就能勝任絕大多數分組列表的需求,例如通訊錄分組、論壇分類、商品分類等場景。

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