編輯:關於 Android 開發
這個範例非常簡單,簡單到初學者都能輕鬆上手。今天的目的只是把效果實現出來。如果想更深入地理解 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 view = (ExpandableListView) findViewById(R.id.elv); TreeAdapter adapter = new TreeAdapter(getApplicationContext()); view.setAdapter(adapter);
<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" 用來隱藏預設的群組指示箭頭,讓畫面更乾淨。這是最濃縮的版本,大家應該很快就能理解並動手實作。
Android Fragment 深度解析:生命周期、底部導航與常見隱患
Android Fragment 深度解析:生命周期、底部導航與常見隱患 Fragment 是 Android 上非常重要的界面組件,特別是在需要構建多面板、底部導航或模
深入解析 android:layout_weight 屬性的運作原理
深入解析 android:layout_weight 屬性的運作原理 layout_weight 是 LinearLayout 中用來按比例分配空間的屬性,但許多人對它的
Android 安全入門:APK 反編譯、資源還原與重新打包解析
從 APK 看 Android 應用安全 Android 應用程式打包後會產生 APK 檔案,而 APK 本質上是一個壓縮包。理解 APK 的結構,是認識 Android
Android 設定頁框架:PreferenceScreen 與 PreferenceFragment 實作
為什麼不用普通布局硬做 設定頁有大量重複模式:一行標題加說明、點擊開對話框、右側帶開關、點擊跳轉。若用一般布局手刻,每個項目都要自己處理點擊、狀態保存、樣式一致性。And