使用了StickyListHeadersListView
这个库的项目很多,因为许多电话本都是用的这个效果,而且有很多项目都使用了这个效果来实现的层级导航:
先看效果:
主要的核心代码是一个Adapter,项目的github的README.md上给了一个示例,sample下也有一个比较麻烦的实现,我主要参考了这两个才明白了使用方式:
Adapter代码:
private class MyAdapter extends BaseAdapter implements StickyListHeadersAdapter{
private String[] mCountries;
private LayoutInflater mInflater;
public MyAdapter(Context context) {
mInflater = LayoutInflater.from(context);
mCountries = context.getResources().getStringArray(R.array.countries);
}
@Override
public View getHeaderView(int i, View view, ViewGroup viewGroup) {
Log.i("TAG","get HeaderView "+i);
HeaderViewHolder holder;
if (view == null) {
holder = new HeaderViewHolder();
view = mInflater.inflate(R.layout.header, viewGroup, false);
holder.text = (TextView) view.findViewById(R.id.text1);
view.setTag(holder);
} else {
holder = (HeaderViewHolder) view.getTag();
}
// set header text as first char in name
CharSequence headerChar = mCountries[i].subSequence(0, 1);
holder.text.setText(headerChar);
return view;
}
/**
* 这个是用来边标记浮动headerView的一个方法,返回相同ID的将被显示为同一View
* @param i 当前位置
* @return 返回唯一ID
*/
@Override
public long getHeaderId(int i) {
Log.i("TAG","get Header ID "+i +" char at "+mCountries[i].subSequence(0, 1).charAt(0));
return mCountries[i].subSequence(0, 1).charAt(0);
}
@Override
public int getCount() {
return mCountries.length;
}
@Override
public Object getItem(int position) {
return mCountries[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("TAG","get View "+ position);
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(Android.R.layout.simple_expandable_list_item_1, parent, false);
holder.text = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(mCountries[position]);
return convertView;
}
class HeaderViewHolder {
TextView text;
}
class ViewHolder {
TextView text;
}
}
主要用此标记HeaderView的就是HeaderID,返回同一ID的将会显示为同一个Header
其他的使用与ListView相同。