---
title: " Anroid ListView分组和悬浮Header实现"
author: "Java-Object"
date: "2014-06-09T21:24:35Z"
tags: []
categories: ["编程语言"]
slug: "anroid-listview-header"
draft: false
lastmod: "2014-06-09T21:26:02Z"
id: 2077689
url: "https://hezd.iteye.com/blog/2077689"
---

转载自：[http://blog.csdn.net/leehong2005/article/details/18810509#comments](http://blog.csdn.net/leehong2005/article/details/18810509#comments)

之前在使用iOS时，看到过一种分组的View，每一组都有一个Header，在上下滑动的时候，会有一个悬浮的Header，这种体验觉得很不错，请看下图：

![](http://img.blog.csdn.net/20140127110217015?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGVlaG9uZzIwMDU=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)

上图中标红的1，2，3，4四张图中，当向上滑动时，仔细观察灰色条的Header变化，当第二组向上滑动时，会把第一组的悬浮Header挤上去。

这种效果在Android是没有的，iOS的SDK就自带这种效果。这篇文章就介绍如何在Android实现这种效果。

## []()1、悬浮Header的实现

其实Android自带的联系人的App中就有这样的效果，我也是把他的类直接拿过来的，实现了**PinnedHeaderListView**这么一个类，扩展于**ListView**，核心原理就是在ListView的最顶部**绘制**一个调用者设置的Header View，在滑动的时候，根据一些状态来决定是否向上或向下移动Header View（其实就是调用其layout方法，理论上在绘制那里作一些平移也是可以的）。下面说一下具体的实现：

**1.1、PinnedHeaderAdapter接口**

这个接口需要ListView的Adapter来实现，它定义了两个方法，一个是让Adapter告诉ListView当前指定的position的数据的状态，比如指定position的数据可能是组的header；另一个方法就是设置Header View，比如设置Header View的文本，图片等，这个方法是由调用者去实现的。

**\[java]** [view plain](http://blog.csdn.net/leehong2005/article/details/18810509 "view plain")[copy](http://blog.csdn.net/leehong2005/article/details/18810509 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/172779 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/172779/fork "派生到我的代码片")

 

01. /\**
02. * Adapter interface.  The list adapter must implement this interface.
03. \*/
04. public interface PinnedHeaderAdapter {
05. /\**
06. * Pinned header state: don't show the header.
07. \*/
08. public static final int PINNED\_HEADER\_GONE = 0;
09. /\**
10. * Pinned header state: show the header at the top of the list.
11. \*/
12. public static final int PINNED\_HEADER\_VISIBLE = 1;
13. /\**
14. * Pinned header state: show the header. If the header extends beyond
15. * the bottom of the first shown element, push it up and clip.
16. \*/
17. public static final int PINNED\_HEADER\_PUSHED\_UP = 2;
18. /\**
19. * Computes the desired state of the pinned header for the given
20. * position of the first visible list item. Allowed return values are
21. * {@link #PINNED\_HEADER\_GONE}, {@link #PINNED\_HEADER\_VISIBLE} or
22. * {@link #PINNED\_HEADER\_PUSHED\_UP}.
23. \*/
24. int getPinnedHeaderState(int position);
25. /\**
26. * Configures the pinned header view to match the first visible list item.
27. \*
28. * @param header pinned header view.
29. * @param position position of the first visible list item.
30. * @param alpha fading of the header view, between 0 and 255.
31. \*/
32. void configurePinnedHeader(View header, int position, int alpha);
33. }

**1.2、如何绘制Header View**

这是在dispatchDraw方法中绘制的：

**\[java]** [view plain](http://blog.csdn.net/leehong2005/article/details/18810509 "view plain")[copy](http://blog.csdn.net/leehong2005/article/details/18810509 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/172779 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/172779/fork "派生到我的代码片")

 

1. @Override
2. protected void dispatchDraw(Canvas canvas) {
3. super.dispatchDraw(canvas);
4. if (mHeaderViewVisible) {
5. drawChild(canvas, mHeaderView, getDrawingTime());
6. }
7. }

**1.3、配置Header View**

核心就是根据不同的状态值来控制Header View的状态，比如PINNED\_HEADER\_GONE（隐藏）的情况，可能需要设置一个flag标记，不绘制Header View，那么就达到隐藏的效果。当PINNED\_HEADER\_PUSHED\_UP状态时，可能需要根据不同的位移来计算Header View的移动位移。下面是具体的实现：

**\[java]** [view plain](http://blog.csdn.net/leehong2005/article/details/18810509 "view plain")[copy](http://blog.csdn.net/leehong2005/article/details/18810509 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/172779 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/172779/fork "派生到我的代码片")

 

01. public void configureHeaderView(int position) {
02. if (mHeaderView == null || null == mAdapter) {
03. return;
04. }
05. int state = mAdapter.getPinnedHeaderState(position);
06. switch (state) {
07. case PinnedHeaderAdapter.PINNED\_HEADER\_GONE: {
08. mHeaderViewVisible = false;
09. break;
10. }
11. case PinnedHeaderAdapter.PINNED\_HEADER\_VISIBLE: {
12. mAdapter.configurePinnedHeader(mHeaderView, position, MAX\_ALPHA);
13. if (mHeaderView.getTop() != 0) {
14. mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight);
15. }
16. mHeaderViewVisible = true;
17. break;
18. }
19. case PinnedHeaderAdapter.PINNED\_HEADER\_PUSHED\_UP: {
20. View firstView = getChildAt(0);
21. int bottom = firstView.getBottom();
22. int itemHeight = firstView.getHeight();
23. int headerHeight = mHeaderView.getHeight();
24. int y;
25. int alpha;
26. if (bottom &lt; headerHeight) {
27. y = (bottom - headerHeight);
28. alpha = MAX\_ALPHA * (headerHeight + y) / headerHeight;
29. } else {
30. y = 0;
31. alpha = MAX\_ALPHA;
32. }
33. mAdapter.configurePinnedHeader(mHeaderView, position, alpha);
34. if (mHeaderView.getTop() != y) {
35. mHeaderView.layout(0, y, mHeaderViewWidth, mHeaderViewHeight + y);
36. }
37. mHeaderViewVisible = true;
38. break;
39. }
40. }
41. }

**1.4、onLayout和onMeasure**

在这两个方法中，控制Header View的位置及大小

**\[java]** [view plain](http://blog.csdn.net/leehong2005/article/details/18810509 "view plain")[copy](http://blog.csdn.net/leehong2005/article/details/18810509 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/172779 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/172779/fork "派生到我的代码片")

 

01. @Override
02. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
03. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
04. if (mHeaderView != null) {
05. measureChild(mHeaderView, widthMeasureSpec, heightMeasureSpec);
06. mHeaderViewWidth = mHeaderView.getMeasuredWidth();
07. mHeaderViewHeight = mHeaderView.getMeasuredHeight();
08. }
09. }
10. @Override
11. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
12. super.onLayout(changed, left, top, right, bottom);
13. if (mHeaderView != null) {
14. mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight);
15. configureHeaderView(getFirstVisiblePosition());
16. }
17. }

好了，到这里，悬浮Header View就完了，各位可能看不到完整的代码，只要明白这几个核心的方法，自己写出来，也差不多了。

## []()2、ListView Section实现

有两种方法实现ListView Section效果，请参考http://cyrilmottier.com/2011/07/05/listview-tips-tricks-2-section-your-listview/

**方法一：**

每一个ItemView中包含Header，通过数据来控制其显示或隐藏，实现原理如下图：  
![](http://img.blog.csdn.net/20140127113844734?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGVlaG9uZzIwMDU=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)

 

**优点：**

1，实现简单，在Adapter.getView的实现中，只需要根据数据来判断是否是header，不是的话，隐藏Item view中的header部分，否则显示。

2，Adapter.getItem(int n)始终返回的数据是在数据列表中对应的第n个数据，这样容易理解。

3，控制header的点击事件更加容易

**缺点：**

1、使用更多的内存，第一个Item view中都包含一个header view，这样会费更多的内存，多数时候都可能header都是隐藏的。

 

**方法二：**

使用不同类型的View：重写getItemViewType(int)和getViewTypeCount()方法。

 

**优点：**

1，允许多个不同类型的item

2，理解更加简单

**缺点：**

1，实现比较复杂

2，得到指定位置的数据变得复杂一些

 

到这里，我的实现方式是选择第二种方案，尽管它的实现方式要复杂一些，但优点比较明显。

 

## []()3、Adapter的实现

这里主要就是说一下getPinnedHeaderState和configurePinnedHeader这两个方法的实现

**\[java]** [view plain](http://blog.csdn.net/leehong2005/article/details/18810509 "view plain")[copy](http://blog.csdn.net/leehong2005/article/details/18810509 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/172779 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/172779/fork "派生到我的代码片")

 

001. private class ListViewAdapter extends BaseAdapter implements PinnedHeaderAdapter {
002. private ArrayList&lt;Contact&gt; mDatas;
003. private static final int TYPE\_CATEGORY\_ITEM = 0;
004. private static final int TYPE\_ITEM = 1;
005. public ListViewAdapter(ArrayList&lt;Contact&gt; datas) {
006. mDatas = datas;
007. }
008. @Override
009. public boolean areAllItemsEnabled() {
010. return false;
011. }
012. @Override
013. public boolean isEnabled(int position) {
014. // 异常情况处理
015. if (null == mDatas || position &lt;  0|| position &gt; getCount()) {
016. return true;
017. }
018. Contact item = mDatas.get(position);
019. if (item.isSection) {
020. return false;
021. }
022. return true;
023. }
024. @Override
025. public int getCount() {
026. return mDatas.size();
027. }
028. @Override
029. public int getItemViewType(int position) {
030. // 异常情况处理
031. if (null == mDatas || position &lt;  0|| position &gt; getCount()) {
032. return TYPE\_ITEM;
033. }
034. Contact item = mDatas.get(position);
035. if (item.isSection) {
036. return TYPE\_CATEGORY\_ITEM;
037. }
038. return TYPE\_ITEM;
039. }
040. @Override
041. public int getViewTypeCount() {
042. return 2;
043. }
044. @Override
045. public Object getItem(int position) {
046. return (position &gt;= 0 && position &lt; mDatas.size()) ? mDatas.get(position) : 0;
047. }
048. @Override
049. public long getItemId(int position) {
050. return 0;
051. }
052. @Override
053. public View getView(int position, View convertView, ViewGroup parent) {
054. int itemViewType = getItemViewType(position);
055. Contact data = (Contact) getItem(position);
056. TextView itemView;
057. switch (itemViewType) {
058. case TYPE\_ITEM:
059. if (null == convertView) {
060. itemView = new TextView(SectionListView.this);
061. itemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH\_PARENT,
062. mItemHeight));
063. itemView.setTextSize(16);
064. itemView.setPadding(10, 0, 0, 0);
065. itemView.setGravity(Gravity.CENTER\_VERTICAL);
066. //itemView.setBackgroundColor(Color.argb(255, 20, 20, 20));
067. convertView = itemView;
068. }
069. itemView = (TextView) convertView;
070. itemView.setText(data.toString());
071. break;
072. case TYPE\_CATEGORY\_ITEM:
073. if (null == convertView) {
074. convertView = getHeaderView();
075. }
076. itemView = (TextView) convertView;
077. itemView.setText(data.toString());
078. break;
079. }
080. return convertView;
081. }
082. @Override
083. public int getPinnedHeaderState(int position) {
084. if (position &lt; 0) {
085. return PINNED\_HEADER\_GONE;
086. }
087. Contact item = (Contact) getItem(position);
088. Contact itemNext = (Contact) getItem(position + 1);
089. boolean isSection = item.isSection;
090. boolean isNextSection = (null != itemNext) ? itemNext.isSection : false;
091. if (!isSection && isNextSection) {
092. return PINNED\_HEADER\_PUSHED\_UP;
093. }
094. return PINNED\_HEADER\_VISIBLE;
095. }
096. @Override
097. public void configurePinnedHeader(View header, int position, int alpha) {
098. Contact item = (Contact) getItem(position);
099. if (null != item) {
100. if (header instanceof TextView) {
101. ((TextView) header).setText(item.sectionStr);
102. }
103. }
104. }
105. }

在**getPinnedHeaderState**方法中，如果第一个item不是section，第二个item是section的话，就返回状态PINNED\_HEADER\_PUSHED\_UP，否则返回PINNED\_HEADER\_VISIBLE。

在**configurePinnedHeader**方法中，就是将item的section字符串设置到header view上面去。

 

**【重要说明】**

Adapter中的数据里面已经包含了section(header)的数据，数据结构中有一个方法来标识它是否是section。那么，在点击事件就要注意了，通过position可能返回的是section数据结构。

 

**数据结构Contact的定义如下：**

**\[java]** [view plain](http://blog.csdn.net/leehong2005/article/details/18810509 "view plain")[copy](http://blog.csdn.net/leehong2005/article/details/18810509 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/172779 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/172779/fork "派生到我的代码片")

 

01. public class Contact {
02. int id;
03. String name;
04. String pinyin;
05. String sortLetter = "#";
06. String sectionStr;
07. String phoneNumber;
08. boolean isSection;
09. static CharacterParser sParser = CharacterParser.getInstance();
10. Contact() {
11. }
12. Contact(int id, String name) {
13. this.id = id;
14. this.name = name;
15. this.pinyin = sParser.getSpelling(name);
16. if (!TextUtils.isEmpty(pinyin)) {
17. String sortString = this.pinyin.substring(0, 1).toUpperCase();
18. if (sortString.matches("\[A-Z]")) {
19. this.sortLetter = sortString.toUpperCase();
20. } else {
21. this.sortLetter = "#";
22. }
23. }
24. }
25. @Override
26. public String toString() {
27. if (isSection) {
28. return name;
29. } else {
30. //return name + " (" + sortLetter + ", " + pinyin + ")";
31. return name + " (" + phoneNumber + ")";
32. }
33. }
34. }

 

**完整的代码**

**\[java]** [view plain](http://blog.csdn.net/leehong2005/article/details/18810509 "view plain")[copy](http://blog.csdn.net/leehong2005/article/details/18810509 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/172779 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/172779/fork "派生到我的代码片")

 

001. package com.lee.sdk.test.section;
002. import java.util.ArrayList;
003. import android.graphics.Color;
004. import android.os.Bundle;
005. import android.view.Gravity;
006. import android.view.View;
007. import android.view.ViewGroup;
008. import android.widget.AbsListView;
009. import android.widget.AdapterView;
010. import android.widget.AdapterView.OnItemClickListener;
011. import android.widget.BaseAdapter;
012. import android.widget.TextView;
013. import android.widget.Toast;
014. import com.lee.sdk.test.GABaseActivity;
015. import com.lee.sdk.test.R;
016. import com.lee.sdk.widget.PinnedHeaderListView;
017. import com.lee.sdk.widget.PinnedHeaderListView.PinnedHeaderAdapter;
018. public class SectionListView extends GABaseActivity {
019. private int mItemHeight = 55;
020. private int mSecHeight = 25;
021. @Override
022. protected void onCreate(Bundle savedInstanceState) {
023. super.onCreate(savedInstanceState);
024. setContentView(R.layout.activity\_main);
025. float density = getResources().getDisplayMetrics().density;
026. mItemHeight = (int) (density * mItemHeight);
027. mSecHeight = (int) (density * mSecHeight);
028. PinnedHeaderListView mListView = new PinnedHeaderListView(this);
029. mListView.setAdapter(new ListViewAdapter(ContactLoader.getInstance().getContacts(this)));
030. mListView.setPinnedHeaderView(getHeaderView());
031. mListView.setBackgroundColor(Color.argb(255, 20, 20, 20));
032. mListView.setOnItemClickListener(new OnItemClickListener() {
033. @Override
034. public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
035. ListViewAdapter adapter = ((ListViewAdapter) parent.getAdapter());
036. Contact data = (Contact) adapter.getItem(position);
037. Toast.makeText(SectionListView.this, data.toString(), Toast.LENGTH\_SHORT).show();
038. }
039. });
040. setContentView(mListView);
041. }
042. private View getHeaderView() {
043. TextView itemView = new TextView(SectionListView.this);
044. itemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH\_PARENT,
045. mSecHeight));
046. itemView.setGravity(Gravity.CENTER\_VERTICAL);
047. itemView.setBackgroundColor(Color.WHITE);
048. itemView.setTextSize(20);
049. itemView.setTextColor(Color.GRAY);
050. itemView.setBackgroundResource(R.drawable.section\_listview\_header\_bg);
051. itemView.setPadding(10, 0, 0, itemView.getPaddingBottom());
052. return itemView;
053. }
054. private class ListViewAdapter extends BaseAdapter implements PinnedHeaderAdapter {
055. private ArrayList&lt;Contact&gt; mDatas;
056. private static final int TYPE\_CATEGORY\_ITEM = 0;
057. private static final int TYPE\_ITEM = 1;
058. public ListViewAdapter(ArrayList&lt;Contact&gt; datas) {
059. mDatas = datas;
060. }
061. @Override
062. public boolean areAllItemsEnabled() {
063. return false;
064. }
065. @Override
066. public boolean isEnabled(int position) {
067. // 异常情况处理
068. if (null == mDatas || position &lt;  0|| position &gt; getCount()) {
069. return true;
070. }
071. Contact item = mDatas.get(position);
072. if (item.isSection) {
073. return false;
074. }
075. return true;
076. }
077. @Override
078. public int getCount() {
079. return mDatas.size();
080. }
081. @Override
082. public int getItemViewType(int position) {
083. // 异常情况处理
084. if (null == mDatas || position &lt;  0|| position &gt; getCount()) {
085. return TYPE\_ITEM;
086. }
087. Contact item = mDatas.get(position);
088. if (item.isSection) {
089. return TYPE\_CATEGORY\_ITEM;
090. }
091. return TYPE\_ITEM;
092. }
093. @Override
094. public int getViewTypeCount() {
095. return 2;
096. }
097. @Override
098. public Object getItem(int position) {
099. return (position &gt;= 0 && position &lt; mDatas.size()) ? mDatas.get(position) : 0;
100. }
101. @Override
102. public long getItemId(int position) {
103. return 0;
104. }
105. @Override
106. public View getView(int position, View convertView, ViewGroup parent) {
107. int itemViewType = getItemViewType(position);
108. Contact data = (Contact) getItem(position);
109. TextView itemView;
110. switch (itemViewType) {
111. case TYPE\_ITEM:
112. if (null == convertView) {
113. itemView = new TextView(SectionListView.this);
114. itemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH\_PARENT,
115. mItemHeight));
116. itemView.setTextSize(16);
117. itemView.setPadding(10, 0, 0, 0);
118. itemView.setGravity(Gravity.CENTER\_VERTICAL);
119. //itemView.setBackgroundColor(Color.argb(255, 20, 20, 20));
120. convertView = itemView;
121. }
122. itemView = (TextView) convertView;
123. itemView.setText(data.toString());
124. break;
125. case TYPE\_CATEGORY\_ITEM:
126. if (null == convertView) {
127. convertView = getHeaderView();
128. }
129. itemView = (TextView) convertView;
130. itemView.setText(data.toString());
131. break;
132. }
133. return convertView;
134. }
135. @Override
136. public int getPinnedHeaderState(int position) {
137. if (position &lt; 0) {
138. return PINNED\_HEADER\_GONE;
139. }
140. Contact item = (Contact) getItem(position);
141. Contact itemNext = (Contact) getItem(position + 1);
142. boolean isSection = item.isSection;
143. boolean isNextSection = (null != itemNext) ? itemNext.isSection : false;
144. if (!isSection && isNextSection) {
145. return PINNED\_HEADER\_PUSHED\_UP;
146. }
147. return PINNED\_HEADER\_VISIBLE;
148. }
149. @Override
150. public void configurePinnedHeader(View header, int position, int alpha) {
151. Contact item = (Contact) getItem(position);
152. if (null != item) {
153. if (header instanceof TextView) {
154. ((TextView) header).setText(item.sectionStr);
155. }
156. }
157. }
158. }
159. }

关于数据加载，分组的逻辑这里就不列出了，数据分组请参考：

[Android 实现ListView的A-Z字母排序和过滤搜索功能，实现汉字转成拼音](http://blog.csdn.net/xiaanming/article/details/12684155)

最后来一张截图：

 

![](http://img.blog.csdn.net/20140306155725140?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGVlaG9uZzIwMDU=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)