Android ListView item 不同布局实现
最重要的是在BaseAdapter里的getItemViewType();(为什么还待考虑)
直接上代码
public class ListAdapter extends BaseAdapter { private Context mContext; private static final int VIEWTYPTOP = 0; private static final int VIEWTYPFIRST = 1; private static final int VIEWTYPSECOND = 2; private LayoutInflater mInflater = null; public Adapter(Activity context) { mContext = context; mInflater = LayoutInflater.from(mContext); } @Override public int getViewTypeCount() { return 3; } /** * 不同布局必须重写此方法 */ @Override public int getItemViewType(int position) { if (position == 0) { return VIEWTYPTOP; } else { if (position % 2 == 0) { return VIEWTYPSECOND; } else { return VIEWTYPFIRST; } } } @Override public int getCount() { return 10; } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup arg2) { ViewHolder mHolder; int type = getItemViewType(position); System.out.println("getView " + position + " " + convertView + " type = " + type); if (convertView == null) { mHolder = new ViewHolder(); switch (type) { case VIEWTYPTOP: convertView = mInflater.inflate(R.layout.top_item,null); mHolder.imgCentent = (ImageView) convertView.findViewById(R.id.img_top); break; case VIEWTYPFIRST: convertView = mInflater.inflate(R.layout.first_item, null); mHolder.imgCentent = (ImageView) convertView.findViewById(R.id.img_first_centent); mHolder.imgLeft = (ImageView) convertView.findViewById(R.id.img_first_left); mHolder.imgRight = (ImageView) convertView.findViewById(R.id.img_first_right); mHolder.txtDate = (TextView) convertView.findViewById(R.id.txt_first_date); mHolder.txtWeek = (TextView) convertView.findViewById(R.id.txt_first_week); break; case VIEWTYPSECOND: convertView = mInflater.inflate(R.layout.second_item, null); mHolder.imgCentent = (ImageView) convertView.findViewById(R.id.img_second_centent); mHolder.imgLeft = (ImageView) convertView.findViewById(R.id.img_second_left); mHolder.imgRight = (ImageView) convertView.findViewById(R.id.img_second_right); mHolder.txtDate = (TextView) convertView.findViewById(R.id.txt_second_date); mHolder.txtWeek = (TextView) convertView.findViewById(R.id.txt_second_week); break; default: break; } convertView.setTag(mHolder); } else { mHolder = (ViewHolder) convertView.getTag(); } switch (type) { case VIEWTYPTOP: break; case VIEWTYPFIRST: mHolder.txtWeek.setText("星期四"); break; default: break; } return convertView; } class ViewHolder { ImageView imgRight; ImageView imgCentent; ImageView imgLeft; TextView txtDate; TextView txtWeek; } }