首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android ExpandableListView 搜尋過濾:雙層資料結構正確實現

     編輯:程式設計疑難解答

需求:EditText/SearchView 關鍵字過濾二級展開列表

ExpandableListView 有「群組 → 子項」兩層資料,過濾邏輯比 ListView 複雜。

核心資料結構


class Group {
    String name;
    List children;
}
List originalData;      // 完整資料
List filteredData;      // 過濾後資料,傳給 Adapter

過濾邏輯(在 Adapter 或 Activity 中)


public void filter(String query) {
    filteredData.clear();
    if (TextUtils.isEmpty(query)) {
        filteredData.addAll(originalData);
    } else {
        for (Group g : originalData) {
            List matchedChildren = new ArrayList<>();
            for (Child c : g.children) {
                if (c.name.toLowerCase().contains(query.toLowerCase())) {
                    matchedChildren.add(c);
                }
            }
            if (!matchedChildren.isEmpty()) {
                Group newGroup = new Group(g.name, matchedChildren);
                filteredData.add(newGroup);
            }
        }
    }
    notifyDataSetChanged(); // 刷新 UI
}

Adapter 關鍵點

  • getGroupCount() 返回 filteredData.size()。
  • getChildrenCount(groupPosition) 返回 filteredData.get(groupPosition).children.size()。
  • getGroup/groupView、getChild/childView 皆從 filteredData 取值。

進階:保持群組展開狀態


// 過濾前記錄展開群組
Set expandedPositions = new HashSet<>();
for (int i = 0; i < expandableListView.getExpandableListAdapter().getGroupCount(); i++) {
    if (expandableListView.isGroupExpanded(i)) expandedPositions.add(i);
}
// 過濾後恢復
for (int pos : expandedPositions) {
    if (pos < filteredData.size()) expandableListView.expandGroup(pos);
}

現成庫推薦

關鍵:**過濾生成新的雙層列表**,而非嘗試在原列表上隱藏 View,避免位置索引錯亂。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved