Android StickyListHeaders实现电话本列表效果
本文实例为大家分享了StickyListHeaders电话本列表效果的具体代码,供大家参考,具体内容如下
效果展示
布局文件
与listview使用方式一样,可以在布局文件中直接进行使用
核心代码
oncreat方法
在oncreat方法中初始化控件,并为控件设置数据适配器
StickyListHeadersListView stickyList = (StickyListHeadersListView) findViewById(R.id.list); MyAdapter adapter = new MyAdapter(this); stickyList.setAdapter(adapter);
设置数据适配器
在设置数据适配器的时候,需要先继承BaseAdapter,然后实现StickyListHeadersAdapter接口,最后实现里面为实现的方法
public class MyAdapter extends BaseAdapter implements StickyListHeadersAdapter { private String[] countries; private LayoutInflater inflater; public MyAdapter(Context context) { inflater = LayoutInflater.from(context); countries = context.getResources().getStringArray(R.array.countries); } @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.text); 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; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)