我制作了以下适配器,以前使用它来创建始终相同的行。我删除了textviews和imageviews的创建。
我要实现的是根据键创建不同的行。一行可以包含文本和图像,而另一行仅包含文本。我将如何做到这一点?
public class DetailsListAdapter extends ArrayAdapter<ArrayList<String>> {
private Context context;
private ArrayList<String> keys;
public DetailsListAdapter(Context context, ArrayList<String> keys) {
super(context,R.layout.details);
this.context = context;
this.keys = keys;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.details, null);
return v;
}
@Override
public int getCount(){
return keys.size();
}
}
要为行添加不同的布局,您需要覆盖getViewItemType
和getViewTypeCount
。
您应该看一下链接中的视频。
http://www.youtube.com/watch?v=wDBM6wVEO70
private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;
private static final int TYPE_ITEM3 = 2;
然后
int type;
@Override
public int getItemViewType(int position) {
if (position== 0){
type = TYPE_ITEM1;
} else if (position == 1){
type = TYPE_ITEM2;
}
else
{
type= TYPE_ITEM3 ;
}
return type;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = null;
int type = getItemViewType(position);
// instead of if else you can use a case
if (convertView == null) {
if (type == TYPE_ITEM1 {
//infalte layout of type1
convertView = mInflater.inflate(R.layout.layouttype1,
parent, false);
}
if (type == TYPE_ITEM2) {
//infalte layout of type2
convertView = mInflater.inflate(R.layout.layouttype2,
parent, false);
} else {
//infalte layout of normaltype
convertView = mInflater.inflate(R.layout.layouttype3,
parent, false);
}
...// rest of the code
return convertView;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句