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

Android 實現 QQ 列表式分類懸浮提示

編輯:關於 Android 程式設計

先看看要實現的效果:

這種效果的核心是自定義一個 ExpandableListView,給它設置一個指示布局,並在滑動過程中實時監聽當前應該懸浮顯示的分類。今天抽空整理了代碼,記錄一下使用過程,方便以後有類似需求時快速搞定。

一、項目結構

上圖三個類分別是自定義的 ExpandableListView、主界面,以及 ExpandableListView 使用的 Adapter;下方幾個 xml 文件則分別是主界面布局、指示器布局、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);

可以看到,構造方法裡傳入了上下文對象、種類、數據,以及我們的 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 實現圖中的懸浮提示效果其實非常容易。以上就是本文的全部內容,希望能給大家的學習或工作帶來幫助,如有疑問歡迎留言交流。

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