第一步:
1 public abstract class DefaultAdapter<T> extends BaseAdapter 2 { 3 4 protected List<T> list; 5 6 public DefaultAdapter(List<T> list) 7 { 8 9 this.list = list; 10 } 11 12 @Override 13 public int getCount() 14 { 15 // TODO Auto-generated method stub 16 return list.size(); 17 } 18 19 @Override 20 public Object getItem(int position) 21 { 22 // TODO Auto-generated method stub 23 return list.get(position); 24 } 25 26 @Override 27 public long getItemId(int position) 28 { 29 // TODO Auto-generated method stub 30 return position; 31 } 32 33 public abstract BaseHolder<T> getHolder(); 34 35 @Override 36 public View getView(int position, View convertView, ViewGroup parent) 37 { 38 // TODO Auto-generated method stub 39 // View view = null; 40 BaseHolder<T> holder = null; 41 42 if (convertView == null) 43 { 44 45 // view = View.inflate(MyApplication.getContext(), R.layout.item_city, null); 46 holder = getHolder(); 47 48 // holder.tv1 = (TextView) view.findViewById(R.id.tv1); 49 // holder.tv2 = (TextView) view.findViewById(R.id.tv2); 50 51 // view.setTag(holder); 52 53 convertView = holder.getView(); 54 55 } 56 57 58 holder = (BaseHolder<T>) convertView.getTag(); 59 holder.initData(list, position); 60 // City city = list.get(position); 61 // holder.tv1.setText(city.getName()); 62 // holder.tv2.setText(city.getPerson()); 63 64 return convertView; 65 } 66 67 }
第二步:
1 public abstract class BaseHolder<T> 2 { 3 4 protected View view = null; 5 6 public BaseHolder() 7 { 8 9 initView(); 10 } 11 12 public View getView() 13 { 14 return view; 15 } 16 17 18 public abstract void initData(List<T> list, int position); 19 20 public abstract void initView(); 21 }
第三步:
1 public class StudentAdapter extends DefaultAdapter 2 { 3 public StudentAdapter(List list) 4 { 5 super(list); 6 } 7 8 @Override 9 public BaseHolder getHolder() 10 { 11 return new ViewHolder(); 12 } 13 14 private class ViewHolder extends BaseHolder 15 { 16 private TextView tvName, tvAge; 17 18 @Override 19 public void initData(List list, int position) 20 { 21 Student student= (Student) list.get(position); 22 tvName.setText(student.getName()); 23 tvAge.setText(String.valueOf(student.getAge())); 24 25 } 26 27 @Override 28 public void initView() 29 { 30 view = View.inflate(MyApplication.getAppContext(), R.layout.item_student_listview, null); 31 tvName = (TextView) view.findViewById(R.id.tv_student_listview_name); 32 tvAge= (TextView) view.findViewById(R.id.tv_student_listview_age); 33 view.setTag(this); 34 } 35 } 36 }
时间: 2024-11-07 05:08:29