效果圖:

這種效果的實現這里是采用自定義ExpandableListView,給它設置一個指示布局,在滑動過程中監聽當前是否應該懸浮顯示分類來實現的。今天抽時間,整理了下代碼,記錄一下使用過程,以便有類似的需求的時候可以快速搞定。
話不多說,我們直接看代碼和使用方法。
一 項目結構

上邊兒三個類分別是我們的自定義ExpandableListView,主界面,以及ExpandableListView使用的Adapter。下邊兒幾個xml文件分別是主界面布局,指示器布局,ExpandableListView子項布局,ExpandableListView組布局。
二 實現代碼
1.在xml中聲明自定義ExpandableListView
<test.com.expandablelistviewdemo.CustomExpandListview //這里不唯一,看你具體把CustomExpandListview放在哪里android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent"></test.com.expandablelistviewdemo.CustomExpandListview>
2.聲明數據源相關(這里為了演示,數據全是String類型,看具體需求可改變)
private String[] parentSource = {"分類1", "分類2", "分類3", "分類4", "分類5"};private ArrayList<String> parent = new ArrayList<>();private Map<String, ArrayList<String>> datas = new HashMap<>();3.初始化演示數據
//種類for (int i = 0; i < parentSource.length; i++) { parent.add(parentSource[i]);}//給每個種類添加模擬數據for (int i = 0; i < parent.size(); i++) { String str = parent.get(i); ArrayList<String> temp = new ArrayList<>(); for (int j = 0; j < 20; j++) { temp.add("" + j); } datas.put(str, temp);}4.初始化Adapter以及使用
myAdapter = new MyAdapter(this, parent, datas, listview);listview.setAdapter(myAdapter);
在初始化adapter的時候,可以看到我們在構造方法中傳入了上下文對象,種類,數據,以及我們的CustomExpandListview對象,所以在CustomExpandListview 中我們要添加相應的構造方法。
5.設置懸浮提示布局
listview.setHeaderView(getLayoutInflater().inflate(R.layout.indictor_layout, listview, false));
6.其他
默認全部展開
for (int i = 0; i < parent.size(); i++) { listview.expandGroup(i);}item點擊事件
listview.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) { Toast.makeText(MainActivity.this, "點擊了第" + (i + 1) + " 類的第" + i1 + "項", Toast.LENGTH_SHORT).show(); return true; }});三 總結
從上邊兒的步驟可以看出,使用CustomExpandListview實現圖中的效果是非常容易的,以上就是這篇文章的全部內容,希望對大家的學習或工作帶來一定的幫助,如果有疑問可以留言交流。
新聞熱點
疑難解答