使用了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相同。