亲宝软件园·资讯

展开

StickyListHeaders电话本列表效果 Android StickyListHeaders实现电话本列表效果

常利兵 人气:0
想了解Android StickyListHeaders实现电话本列表效果的相关内容吗,常利兵在本文为您仔细讲解StickyListHeaders电话本列表效果的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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;
}

}

加载全部内容

相关教程
猜你喜欢
用户评论