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

Android ExpandableListView 可展開列表控件完整實作教學

編輯:關於 Android 程式設計

手機 QQ 的好友列表為什麼看起來那麼好用?就是因為它把「分組」與「成員」兩層資訊疊在一起,點一下標題就能收合或展開。即便你暫時不需要這種效果,多認識一個控件總不是壞事。

本文要介紹的 ExpandableListView,可以理解為普通 ListView 的進階版本:它能自由收合與展開分組,結構清楚、視覺上也更有層次。下面的示範介面刻意做得很樸素,目的是讓你把注意力放在邏輯上,外觀你可以自行美化。

先準備三個 XML 版面檔

這個控件至少需要三份版面資源:主介面、一級標題(group)樣式、二級內容(child)樣式。

main.xml:主介面

結構非常單純,只需要一個 ExpandableListView:

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

    <ExpandableListView
        android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

groups.xml:一級標題樣式

放上一個 TextView 作為分組標題即可,這裡用 paddingLeft 讓文字有點內縮:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/textGroup"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingLeft="40px"
        android:paddingTop="6px"
        android:paddingBottom="6px"
        android:textSize="15sp"
        android:text="No data" />
</LinearLayout>

childs.xml:二級內容樣式

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/textChild"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingLeft="60px"
        android:paddingTop="10px"
        android:paddingBottom="10px"
        android:textSize="20sp"
        android:text="No Data" />
</LinearLayout>

撰寫主程式 ExpandActivity

這裡繼承 ExpandableListActivity,好處是可以直接用 setListAdapter()。資料來源用兩層 Map 結構描述:外層是一級集合,內層是二級集合。

public class ExpandActivity extends ExpandableListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 一級條目
        Map<String, String> title_1 = new HashMap<String, String>();
        Map<String, String> title_2 = new HashMap<String, String>();
        title_1.put("group", "開發");
        title_2.put("group", "管理");

        List<Map<String, String>> groups = new ArrayList<Map<String, String>>();
        groups.add(title_1);
        groups.add(title_2);

        // 二級條目(開發)
        Map<String, String> content_1 = new HashMap<String, String>();
        Map<String, String> content_2 = new HashMap<String, String>();
        content_1.put("child", "VC++");
        content_2.put("child", "Java");
        List<Map<String, String>> childs_1 = new ArrayList<Map<String, String>>();
        childs_1.add(content_1);
        childs_1.add(content_2);

        // 二級條目(管理)
        Map<String, String> content_3 = new HashMap<String, String>();
        Map<String, String> content_4 = new HashMap<String, String>();
        content_3.put("child", "敏捷開發");
        content_4.put("child", "迭代開發");
        List<Map<String, String>> childs_2 = new ArrayList<Map<String, String>>();
        childs_2.add(content_3);
        childs_2.add(content_4);

        // 把兩組二級資料放進外層容器
        List<List<Map<String, String>>> childs = new ArrayList<List<Map<String, String>>>();
        childs.add(childs_1);
        childs.add(childs_2);

        // SimpleExpandableListAdapter 的九個參數依序為:
        // 1. Context
        // 2. 一級資料集合      3. 一級樣式版面      4. 一級取值鍵      5. 一級顯示控件 ID
        // 6. 二級資料集合      7. 二級樣式版面      8. 二級取值鍵      9. 二級顯示控件 ID
        SimpleExpandableListAdapter sela = new SimpleExpandableListAdapter(
                this,
                groups, R.layout.groups, new String[]{"group"}, new int[]{R.id.textGroup},
                childs, R.layout.childs, new String[]{"child"}, new int[]{R.id.textChild}
        );

        setListAdapter(sela);
    }
}

這裡要特別提醒:樣式檔放在 res/layout 目錄下,因此資源 ID 前綴應為 R.layout(例如 R.layout.groups),而不是 R.drawable。原始教學常寫成 R.drawable.groups,那會在編譯期就出錯。命名也建議避開 groups、childs 這類容易與系統資源混淆的名稱,改用 item_group.xml、item_child.xml 會更清楚。

回應點擊事件

想要處理使用者操作,只要覆寫對應方法:

// 二級內容被點擊
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
    return super.onChildClick(parent, v, groupPosition, childPosition, id);
}

// 二級項目被選取
@Override
public boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup) {
    return super.setSelectedChild(groupPosition, childPosition, shouldExpandGroup);
}

// 一級標題被選取
@Override
public void setSelectedGroup(int groupPosition) {
    super.setSelectedGroup(groupPosition);
}

寫完之後把專案跑上模擬器或真機,就能看到收合展開的效果。

改成「控件化」寫法

如果你不想繼承 ExpandableListActivity,改成一般的 Activity 也完全可行,差別只在取得控件的方式:

private ExpandableListView expandList;

// onCreate 中
expandList = (ExpandableListView) findViewById(R.id.elv);
expandList.setAdapter(sela);

事件部分則自行掛上 OnGroupClickListener、OnChildClickListener 等 Listener 即可,彈性更高。

進階:自訂 BaseExpandableListAdapter

當版面需要動態生成、或資料結構較複雜時,SimpleExpandableListAdapter 會不夠用,這時就繼承 BaseExpandableListAdapter 自行實作。

先在 main.xml 放好控件,並用 indicatorRight 調整展開箭頭與左邊緣的間距:

<ExpandableListView
    android:id="@+id/elv"
    android:indicatorRight="160dp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
</ExpandableListView>
<!-- indicatorRight:小圖示右邊緣與 ExpandableListView 左邊緣的距離 -->

資料模型:

class ElvObject {
    String groupName = "";
    ArrayList<String> childs = new ArrayList<String>();

    ElvObject(String groupName, ArrayList<String> childs) {
        this.groupName = groupName;
        this.childs = childs;
    }
}

自訂 Adapter:

public class ElvAdapter extends BaseExpandableListAdapter {
    ArrayList<ElvObject> objs;
    Context context;

    ElvAdapter(Context context, ArrayList<ElvObject> objs) {
        this.objs = objs;
        this.context = context;
    }

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

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

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parent) {
        TextView tv = new TextView(context);
        tv.setText(objs.get(groupPosition).childs.get(childPosition));
        tv.setLayoutParams(new ExpandableListView.LayoutParams(
                ExpandableListView.LayoutParams.FILL_PARENT,
                ExpandableListView.LayoutParams.WRAP_CONTENT));
        return tv;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return objs.get(groupPosition).childs.size();
    }

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

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

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

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        TextView tv = new TextView(context);
        tv.setText(objs.get(groupPosition).groupName);
        ExpandableListView.LayoutParams params = new ExpandableListView.LayoutParams(
                ExpandableListView.LayoutParams.FILL_PARENT, 60);
        tv.setLayoutParams(params);
        return tv;
    }

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

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

主程式:

public class AndroidTestActivity extends Activity {
    ExpandableListView elv;
    ElvAdapter adapter;
    ArrayList<ElvObject> objs = new ArrayList<ElvObject>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        elv = (ExpandableListView) findViewById(R.id.elv);
        adapter = new ElvAdapter(this, objs);
        elv.setAdapter(adapter);

        ArrayList<String> list = new ArrayList<String>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        objs.add(new ElvObject("英文", list));

        ArrayList<String> list2 = new ArrayList<String>();
        list2.add("111");
        list2.add("222");
        list2.add("333");
        list2.add("444");
        objs.add(new ElvObject("數字", list2));
    }
}

兩種寫法各有適用場景:資料單純、只要顯示文字時,SimpleExpandableListAdapter 幾行就能搞定;需要客製化每一列的元件、圖示或多欄排版時,就換成自訂 Adapter。另外,自訂 Adapter 中的 convertView 目前沒有複用,實務上建議加上 ViewHolder 模式,避免大量建立物件造成滑動卡頓。

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