1:FragmentHack4.java
/** * Created by y on 15-1-2. */public class FragmentHack4 extends Fragment{ View view; Listnames; ListView lvNames; NameSectionAdapter adapter; TextView tvHeader; int topVisiblePos; @Override public void onAttach(Activity activity) { super.onAttach(activity); names = new ArrayList (); //测试数据 String []t={"A","B","C","D","E","F"}; for(int i=0;i
2:NameSectionAdapter.java
/** * Created by y on 15-1-2. */public class NameSectionAdapter extends ArrayAdapter{ private int resourceId; public NameSectionAdapter(Context context, int resourceId, List objects){ super(context,resourceId,objects); this.resourceId = resourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { String name = getItem(position); ViewHolder holder; if(convertView==null){ convertView = LayoutInflater.from(getContext()).inflate(resourceId,null); holder = new ViewHolder(); holder.tvHeader = (TextView)convertView.findViewById(R.id.tvHeader); holder.tvName = (TextView)convertView.findViewById(R.id.tvName); convertView.setTag(holder); }else{ holder = (ViewHolder)convertView.getTag(); } holder.tvName.setText(name); //如果是第一项或者首字母发生了变化,则显示分组栏,否则隐藏 if(position==0 || getItem(position-1).charAt(0)!=name.charAt(0)){ holder.tvHeader.setVisibility(View.VISIBLE); holder.tvHeader.setText(name.substring(0,1)); }else{ holder.tvHeader.setVisibility(View.GONE); } return convertView; } static class ViewHolder{ public TextView tvHeader; public TextView tvName; }}
3:布局文件:
(1)fragment_hack4.xml
(2)list_header.xml
(3)list_name_item.xml
4:运行结果