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

ExpandableListView 分組列表完整實作教學

編輯:關於 Android 程式設計

要做類似即時通訊軟體裡「分組/聯絡人」那種可展開的兩級列表,ExpandableListView 是最直接的選擇。下面用一個完整範例走一遍:實體設計、Adapter 覆寫、佈局與樣式設定。

一、資料結構

兩級列表需要兩個實體:GroupBean 負責分組本身(組名、組描述、成員集合),UserBean 負責成員。

public class GroupBean {
    private String groupName;          // 組名
    private String groupDesc;          // 組描述
    private List<UserBean> userBeans;  // 該組的成員

    public GroupBean(String groupName, String groupDesc, List<UserBean> userBeans) {
        this.groupName = groupName;
        this.groupDesc = groupDesc;
        this.userBeans = userBeans;
    }
    // getter / setter 省略
}

public class UserBean {
    private String name;
    public UserBean(String name) { this.name = name; }
    // getter / setter 省略
}

二、主 Activity

public class MainActivity extends Activity {

    private ExpandableListView expandableListView;
    private ExpandableListViewAdapter adapter;

    private final List<GroupBean> listGroup = new ArrayList<>();

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

        expandableListView = (ExpandableListView) findViewById(R.id.exl);

        List<UserBean> child1 = new ArrayList<>();
        child1.add(new UserBean("組員 A"));
        child1.add(new UserBean("組員 B"));
        child1.add(new UserBean("組員 C"));

        List<UserBean> child2 = new ArrayList<>();
        child2.add(new UserBean("組員 D"));
        child2.add(new UserBean("組員 E"));

        listGroup.add(new GroupBean("分組一", "12/30", child1));
        listGroup.add(new GroupBean("分組二", "5/18", child2));

        adapter = new ExpandableListViewAdapter(this, listGroup);
        expandableListView.setAdapter(adapter);

        // 預設全部展開;若要預設收合改用 collapseGroup(i)
        int groupCount = adapter.getGroupCount();
        for (int i = 0; i < groupCount; i++) {
            expandableListView.expandGroup(i);
        }

        // 點擊分組標題
        expandableListView.setOnGroupClickListener((parent, v, groupPosition, id) -> false);

        // 點擊子項
        expandableListView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
            UserBean user = adapter.getChild(groupPosition, childPosition);
            Toast.makeText(MainActivity.this, user.getName(), Toast.LENGTH_SHORT).show();
            return false;
        });
    }
}

兩個監聽器的回傳值別忽略:回傳 true 表示事件已被消費,展開/收合等預設行為不會再觸發。

三、佈局檔

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

    <ExpandableListView
        android:id="@+id/exl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:cacheColorHint="@android:color/transparent"
        android:childDivider="@color/mainLine"
        android:divider="@color/mainLine"
        android:dividerHeight="0.5dp"
        android:groupIndicator="@null" />

</LinearLayout>

幾個實務上很常被忽略的屬性:

- cacheColorHint:不設的話拖動過程中列表背景會是黑的,通常設成透明。
- divider / dividerHeight:分組之間的分隔線。
- childDivider:子項之間的分隔線,與 divider 是分開的兩組設定。
- groupIndicator:左側那個展開箭頭,設成 @null 就能拿掉,改用自訂的 CheckBox 或圖示呈現狀態。

四、Adapter 實作

繼承 BaseExpandableListAdapter,需要覆寫的方法可以分成兩組:一組回答「有多少、是什麼」(getGroupCount、getChildrenCount、getGroup、getChild、getGroupId、getChildId、hasStableIds、isChildSelectable),另一組負責「怎麼畫」(getGroupView、getChildView)。

public class ExpandableListViewAdapter extends BaseExpandableListAdapter {

    private final Context context;
    private final List<GroupBean> listGroup;

    public ExpandableListViewAdapter(Context context, List<GroupBean> listGroup) {
        this.context = context;
        this.listGroup = listGroup;
    }

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

    @Override
    public int getChildrenCount(int groupPosition) {
        return listGroup.get(groupPosition).getUserBeans().size();
    }

    @Override
    public GroupBean getGroup(int groupPosition) {
        return listGroup.get(groupPosition);
    }

    @Override
    public UserBean getChild(int groupPosition, int childPosition) {
        return listGroup.get(groupPosition).getUserBeans().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 false; }

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

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.group_layout, parent, false);
        }
        GroupBean group = getGroup(groupPosition);
        CheckBox checkBox = convertView.findViewById(R.id.chb_group);
        ((TextView) convertView.findViewById(R.id.tev_group_name)).setText(group.getGroupName());
        ((TextView) convertView.findViewById(R.id.tev_group_desc)).setText(group.getGroupDesc());
        checkBox.setChecked(isExpanded);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.child_layout, parent, false);
        }
        ((TextView) convertView.findViewById(R.id.tev_child))
                .setText(getChild(groupPosition, childPosition).getName());
        return convertView;
    }
}

兩個容易翻車的細節:getGroupView 原本示範中沒有複用 convertView,每次都要重新 inflate,列表滾動時會明顯卡頓,加上 null 判斷是必要的;inflate 時建議傳 parent 並帶 false,讓系統能正確套用 LayoutParams。另外 isChildSelectable 回傳 true,子項才會有點擊效果。

五、子項與分組樣式

group_layout.xml 與 child_layout.xml 都是「外層 LinearLayout 撐滿寬度 + 內層水平排列」的結構,差別只在內容:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingLeft="12dp"
        android:paddingRight="12dp">

        <CheckBox
            android:id="@+id/chb_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:clickable="false"
            android:drawableLeft="@drawable/checkbox_background"
            android:focusable="false" />

        <TextView
            android:id="@+id/tev_group_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/tev_group_desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/secondText"
            android:textSize="12sp" />

    </LinearLayout>
</LinearLayout>

CheckBox 那三個屬性(button=@null、clickable=false、focusable=false)是為了讓它「只顯示、不搶事件」,點擊仍然由整個分組行處理,這點在做自相容展開狀態時很關鍵。中間那個 weight=1 的空 View 則是把右側描述推到最右邊的常見技巧。

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