使用了
StickyListHeadersListView
这个库的项目很多,因为许多电话本都是用的这个效果,而且有很多项目都使用了这个效果来实现的层级导航:
先看效果:
主要的核心代码是一个Adapter,项目的github的README.md上给了一个示例,sample下也有一个比较麻烦的实现,我主要参考了这两个才明白了使用方式:
Adapter代码:
1 private class MyAdapter extends BaseAdapter implements StickyListHeadersAdapter{ 2 3 private String[] mCountries; 4 private LayoutInflater mInflater; 5 6 public MyAdapter(Context context) { 7 mInflater = LayoutInflater.from(context); 8 mCountries = context.getResources().getStringArray(R.array.countries); 9 } 10 @Override 11 public View getHeaderView(int i, View view, ViewGroup viewGroup) { 12 Log.i("TAG","get HeaderView "+i); 13 HeaderViewHolder holder; 14 15 if (view == null) { 16 holder = new HeaderViewHolder(); 17 view = mInflater.inflate(R.layout.header, viewGroup, false); 18 holder.text = (TextView) view.findViewById(R.id.text1); 19 view.setTag(holder); 20 } else { 21 holder = (HeaderViewHolder) view.getTag(); 22 } 23 24 // set header text as first char in name 25 CharSequence headerChar = mCountries[i].subSequence(0, 1); 26 holder.text.setText(headerChar); 27 28 return view; 29 } 30 31 /** 32 * 这个是用来边标记浮动headerView的一个方法,返回相同ID的将被显示为同一View 33 * @param i 当前位置 34 * @return 返回唯一ID 35 */ 36 @Override 37 public long getHeaderId(int i) { 38 Log.i("TAG","get Header ID "+i +" char at "+mCountries[i].subSequence(0, 1).charAt(0)); 39 return mCountries[i].subSequence(0, 1).charAt(0); 40 } 41 42 @Override 43 public int getCount() { 44 return mCountries.length; 45 } 46 47 @Override 48 public Object getItem(int position) { 49 return mCountries[position]; 50 } 51 52 @Override 53 public long getItemId(int position) { 54 return position; 55 } 56 57 @Override 58 public View getView(int position, View convertView, ViewGroup parent) { 59 Log.i("TAG","get View "+ position); 60 ViewHolder holder; 61 62 if (convertView == null) { 63 holder = new ViewHolder(); 64 convertView = mInflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false); 65 holder.text = (TextView) convertView.findViewById(android.R.id.text1); 66 convertView.setTag(holder); 67 } else { 68 holder = (ViewHolder) convertView.getTag(); 69 } 70 71 holder.text.setText(mCountries[position]); 72 73 return convertView; 74 } 75 76 class HeaderViewHolder { 77 TextView text; 78 } 79 80 class ViewHolder { 81 TextView text; 82 } 83 }
主要用此标记HeaderView的就是HeaderID,返回同一ID的将会显示为同一个Header
其他的使用与ListView相同。
时间: 2024-11-02 21:53:34