大家都知道,ListView中的数据是经过adapter适配到屏幕上的,所以要实现listview中每一个item的内容需要去操作adapter中的代码:
在使用不同布局的时候我们要重构以下两个方法:getItemViewType和getViewTypeCount.
public class MyAdapter extends BaseAdapter { ArrayList<String> ls; Context mContext; LinearLayout linearLayout = null; LayoutInflater inflater; TextView tex; final int VIEW_TYPE = 3; final int TYPE_1 = 0; final int TYPE_2 = 1; final int TYPE_3 = 2; public MyAdapter(ArrayList<String> list, Context context) { mContext = context; ls = list; } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } @Override public int getViewTypeCount() { return 3; } @Override public int getCount() { return ls.size(); } @Override public Object getItem(int position) { return ls.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder1 holder1 = null; ViewHolder2 holder2 = null; ViewHolder3 holder3 = null; int type = getItemViewType(position); if (convertView == null) { inflater = LayoutInflater.from(mContext); switch (type) { case TYPE_1: convertView = inflater.inflate(R.layout.layout_item1, parent, false); holder1 = new ViewHolder1(); holder1.tv1 = (TextView) convertView.findViewById(R.id.tv1); convertView.setTag(holder1); break; case TYPE_2: convertView = inflater.inflate(R.layout.layout_item2, parent, false); holder2 = new ViewHolder2(); holder2.tv2 = (TextView) convertView.findViewById(R.id.tv2); convertView.setTag(holder2); break; case TYPE_3: convertView = inflater.inflate(R.layout.layout_item3,parent,false); holder3 = new ViewHolder3(); holder3.tv3 = (TextView)convertView.findViewById(R.id.tv3); convertView.setTag(holder3); } }else{ switch (type){ case TYPE_1: holder1 = (ViewHolder1)convertView.getTag(); break; case TYPE_2: holder2 = (ViewHolder2)convertView.getTag(); break; case TYPE_3: holder3 = (ViewHolder3)convertView.getTag(); break; } } switch (type){ case TYPE_1: holder1.tv1.setText("我是第一个"+(position + 1)); break; case TYPE_2: holder2.tv2.setText("我是第二个"+(position + 1)); break; case TYPE_3: holder3.tv3.setText("我是三个"+(position + 1)); break; } return convertView; } public static class ViewHolder1 { TextView tv1; } public static class ViewHolder2 { TextView tv2; } public static class ViewHolder3 { TextView tv3; } }
创建不同的ViewHolder,通过调用返回的type类型来确定是哪一个item就可以了。
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-10 14:26:12