干貨,仿qq列表,手把手實現(xiàn)分類懸浮提示

新來的產(chǎn)品提了一個需求,讓應(yīng)用中的一個列表按照分類顯示,并且能提示當(dāng)前是在哪個分類,度娘了一番,參考了前輩們的博客,實現(xiàn)了如下圖的效果:

效果圖.gif

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

一 項目結(jié)構(gòu)

項目結(jié)構(gòu).PNG

上邊兒三個類分別是我們的自定義ExpandableListView,主界面,以及ExpandableListView使用的Adapter。下邊兒幾個xml文件分別是主界面布局,指示器布局,ExpandableListView子項布局,ExpandableListView組布局。

二 實現(xiàn)代碼

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.聲明數(shù)據(jù)源相關(guān)(這里為了演示,數(shù)據(jù)全是String類型,看具體需求可改變)

private String[] parentSource = {"分類1", "分類2", "分類3", "分類4", "分類5"};
private ArrayList<String> parent = new ArrayList<>();
private Map<String, ArrayList<String>> datas = new HashMap<>();

3.初始化演示數(shù)據(jù)

//種類
for (int i = 0; i < parentSource.length; i++) {    
parent.add(parentSource[i]);
}
//給每個種類添加模擬數(shù)據(jù)
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的時候,可以看到我們在構(gòu)造方法中傳入了上下文對象,種類,數(shù)據(jù),以及我們的CustomExpandListview對象,所以在CustomExpandListview 中我們要添加相應(yīng)的構(gòu)造方法。

5.設(shè)置懸浮提示布局

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;    
   }
}
);

三 總結(jié)

從上邊兒的步驟可以看出,使用CustomExpandListview實現(xiàn)圖中的效果是非常容易的,這個demo的全部代碼在https://github.com/SolveBugs/ExpandableListviewDemo , 歡迎下載,主要的實現(xiàn)在MyAdapter和CustomExpandListview中,都有非常清楚的注釋。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容