要想设置不同的item需要在adapter里面重写两个方法
getItemViewType() 需要注意这个个类型是0开始
getViewTypeCount();
1 package com.example.listview_01; 2 3 import java.util.List; 4 5 import android.content.Context; 6 import android.view.LayoutInflater; 7 import android.view.View; 8 import android.view.ViewGroup; 9 import android.widget.BaseAdapter; 10 import android.widget.TextView; 11 12 public class MyAdapter extends BaseAdapter { 13 14 private Context context; 15 private List<ViewItem> list; 16 private LayoutInflater inflater; 17 18 public MyAdapter(Context context, List<ViewItem> list) { 19 this.context = context; 20 this.list = list; 21 inflater = LayoutInflater.from(context); 22 } 23 24 @Override 25 public int getCount() { 26 return list.size(); 27 } 28 29 @Override 30 public Object getItem(int position) { 31 return list.get(position); 32 } 33 34 @Override 35 public long getItemId(int position) { 36 return position; 37 } 38 39 @Override 40 public int getItemViewType(int position) { 41 return list.get(position).getType(); 42 } 43 44 @Override 45 public int getViewTypeCount() { 46 return 2; 47 } 48 49 @Override 50 public View getView(int position, View convertView, ViewGroup parent) { 51 HolderType1 holderType1 = null; 52 HolderType2 holderType2 = null; 53 int type = getItemViewType(position); 54 if (convertView == null) { 55 // 根据不同的type设置不同的布局 56 switch (type) { 57 case 0: 58 convertView = inflater.inflate(R.layout.activity_item, null); 59 holderType1 = new HolderType1(convertView); 60 convertView.setTag(holderType1); 61 break; 62 63 case 1: 64 convertView = inflater.inflate(R.layout.activity_item2, null); 65 holderType2 = new HolderType2(convertView); 66 convertView.setTag(holderType2); 67 break; 68 } 69 } else { 70 // 根据不同的布局设置不同的holder 71 switch (type) { 72 case 0: 73 holderType1 = (HolderType1) convertView.getTag(); 74 break; 75 case 1: 76 holderType2 = (HolderType2) convertView.getTag(); 77 break; 78 } 79 } 80 81 ViewItem item = list.get(position); 82 // 根据不同的布局给控件填充数据 83 switch (type) { 84 case 0: 85 holderType1.addressTxt.setText(item.getAddress()); 86 holderType1.nameTxt.setText(item.getName()); 87 holderType1.ageTxt.setText(item.getAge()); 88 break; 89 case 1: 90 holderType2.titleTxt.setText(item.getTitle()); 91 break; 92 } 93 return convertView; 94 } 95 96 private class HolderType1 { 97 public TextView nameTxt; 98 public TextView ageTxt; 99 public TextView addressTxt; 100 101 public HolderType1(View convertView) { 102 nameTxt = (TextView) convertView.findViewById(R.id.name); 103 ageTxt = (TextView) convertView.findViewById(R.id.age); 104 addressTxt = (TextView) convertView.findViewById(R.id.address); 105 } 106 } 107 108 private class HolderType2 { 109 public TextView titleTxt; 110 111 public HolderType2(View convertView) { 112 titleTxt = (TextView) convertView.findViewById(R.id.title); 113 } 114 } 115 116 }
时间: 2024-11-08 20:22:07