您好,登錄后才能下訂單哦!
本文實例為大家分享了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; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。