1.首先 gradel
compile 'se.emilsjolander:stickylistheaders:x.x.x'
用最新版本号代替x.x.x ,我这里使用的是 2.1.1
2.Adapter
public class MyAdapter extends BaseAdapter implements StickyListHeadersAdapter { private String[] countries={"上海","上海","上海","上海","上海","上海","上海","上海","北京","北京","北京","北京","北京","北京","北京","深圳","深圳","深圳","深圳","广州","广州","广州","广州","合肥","大连","耒阳","耒阳","耒阳","耒阳","长沙","湖南","湖南","湖南","湖南","益阳","张家界","欣欣","刘德华","张学友"}; private LayoutInflater inflater; public MyAdapter(Context context) { inflater = LayoutInflater.from(context); } @Override public int getCount() { return countries.length; } @Override public Object getItem(int position) { return countries[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.test_list_item_layout, parent, false); holder.text = (TextView) convertView.findViewById(R.id.text); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.text.setText(countries[position]); return convertView; } @Override public View getHeaderView(int position, View convertView, ViewGroup parent) { HeaderViewHolder holder; if (convertView == null) { holder = new HeaderViewHolder(); convertView = inflater.inflate(R.layout.header, parent, false); holder.text = (TextView) convertView.findViewById(R.id.text1); convertView.setTag(holder); } else { holder = (HeaderViewHolder) convertView.getTag(); } //set header text as first char in name String headerText = "" + countries[position].subSequence(0, 1).charAt(0); holder.text.setText(headerText); return convertView; } @Override public long getHeaderId(int position) { //return the first character of the country as ID because this is what headers are based upon return countries[position].subSequence(0, 1).charAt(0); } class HeaderViewHolder { TextView text; } class ViewHolder { TextView text; }
3.xml
header.xmltest_list_item_layout.xml<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/header_selector" > <TextView android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="start|left" android:padding="5dp" android:textColor="@android:color/white" android:textSize="17sp" android:textStyle="bold" /> </RelativeLayout>
3.在activity中调用<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:paddingBottom="20dp" android:paddingTop="20dp"/>
4.效果图StickyListHeadersListView stickyList = (StickyListHeadersListView) findViewById(R.id.list); MyAdapter adapter = new MyAdapter(this); stickyList.setAdapter(adapter);