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

Android 樹狀清單實作:ExpandableListView 入門(一)

編輯:關於 Android 開發

Android 樹狀清單實作:ExpandableListView 入門(一)

這個範例非常簡單,簡單到初學者都能輕鬆上手。今天的目的只是把效果實現出來。如果想更深入地理解 ExpandableListView,市面上有不少優質的探討文章值得參考。

ExpandableListView 的幾個特殊屬性

參考資源:

https://blog.csdn.net/t12x3456/article/details/7828620

https://www.apkbus.com/thread-124715-1-1.html

自訂適配器

和使用 ListView 時一樣,我們這裡需要繼承一個適配器,叫做 BaseExpandableListAdapter,然後覆寫幾個父類別的方法:

package com.example.uitest;

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

public class TreeAdapter extends BaseExpandableListAdapter {

    Context context;

    public TreeAdapter(Context context) {
        super();
        this.context = context;
    }

    @Override
    public Object getChild(int arg0, int arg1) {
        return 0;
    }

    @Override
    public long getChildId(int arg0, int arg1) {
        return 0;
    }

    @Override
    public View getChildView(int arg0, int arg1, boolean arg2, View v, ViewGroup arg4) {
        v = LayoutInflater.from(context).inflate(R.layout.item2, null);
        return v;
    }

    @Override
    public int getChildrenCount(int arg0) {
        return 3;
    }

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

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

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

    @Override
    public View getGroupView(int arg0, boolean arg1, View v, ViewGroup vgs) {
        v = LayoutInflater.from(context).inflate(R.layout.item_autocomplete, null);
        return v;
    }

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

    @Override
    public boolean isChildSelectable(int arg0, int arg1) {
        return false;
    }
}

這裡我們只實作了四個關鍵函式,分別是:

getChildrenCount(int):取得二級清單的子項目總數,也就是行數。
getGroupCount():取得一級清單的行數。
getChildView(...):取得二級清單的項目版面配置。
getGroupView(...):取得一級清單的項目版面配置。

把適配器載入 ExpandableListView

最後將適配器設定給 ExpandableListView:

ExpandableListView view = (ExpandableListView) findViewById(R.id.elv);
TreeAdapter adapter = new TreeAdapter(getApplicationContext());
view.setAdapter(adapter);

主版面 XML

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

    <ExpandableListView
        android:id="@+id/elv"
        android:layout_width="fill_parent"
        android:groupIndicator="@null"
        android:layout_height="wrap_content"></ExpandableListView>

</LinearLayout>

這裡的 android:groupIndicator="@null" 用來隱藏預設的群組指示箭頭,讓畫面更乾淨。這是最濃縮的版本,大家應該很快就能理解並動手實作。

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