转载 向前冲org
主类关键代码如下:
//添加数据 public List<ViewItem> getData() { list = new ArrayList<ViewItem>(); for (int i = 0; i < 20; i++) { ViewItem item = new ViewItem();//这个必须在这里new 不然 数据都是一样的 if (i % 3 == 0) { item.type = 0; } else { item.type = 1; } item.address = "tianjin" + i; item.name = "wang" + i; list.add(item); } return list; }
适配器代码如下:
public class PlayAdapter extends BaseAdapter { /** * 标题的item */ public static final int ITEM_TITLE = 0; /** * 二级菜单的item */ public static final int ITEM_INTRODUCE = 1; private List<ViewItem> mList; private Context context; private LayoutInflater inflater; // 两个样式 两个holder。100就写100holder。。当然你何以把他抽离出来这里先只为了说明问题 class Holder1 { TextView play_title; Holder1(View view) { play_title = (TextView) view.findViewById(R.id.play_title); } } class Holder2 { TextView play_introduce_title; ImageView play_iv; Holder2(View view) { play_introduce_title = (TextView) view .findViewById(R.id.play_introduce_title); play_iv = (ImageView) view.findViewById(R.id.play_iv); } } public PlayAdapter(Context context, List<ViewItem> mList) { this.context = context; this.mList = mList; inflater = LayoutInflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub System.out.println("mList.size()" + mList.size()); return mList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return mList.get(arg0); } //返回 代表某一个样式 的 数值 @Override public int getItemViewType(int position) { // TODO Auto-generated method stub return mList.get(position).type; } //两个样式 返回2 @Override public int getViewTypeCount() { // TODO Auto-generated method stub return 2; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { int type = getItemViewType(position); Holder1 holder1 = null; Holder2 holder2 = null; System.out.println("getView " + position + " " + convertView + " type = " + type); if (convertView == null) { //选择某一个样式。。 switch (type) { case ITEM_TITLE: convertView = inflater.inflate(R.layout.play_item_title, null); holder1 = new Holder1(convertView); holder1.play_title.setText(mList.get(position).name); convertView.setTag(holder1); break; case ITEM_INTRODUCE: convertView = inflater.inflate(R.layout.paly_item_introduce, null); holder2 = new Holder2(convertView); holder2.play_introduce_title .setText(mList.get(position).address); convertView.setTag(holder2); break; default: break; } } else { switch (type) { case ITEM_TITLE: holder1 = (Holder1) convertView.getTag(); holder1.play_title.setText(mList.get(position).name); break; case ITEM_INTRODUCE: holder2 = (Holder2) convertView.getTag(); holder2.play_introduce_title .setText(mList.get(position).address); break; default: break; } } return convertView; } }如果想看一下例子的小盆友,可以点击链接 点击下载