ListView中的自定义行与自定义适配器

时间:2013-12-11 11:30:13

标签: android listview adapter

我创建了以前使用的以下适配器来创建始终相同的行。我删除了textviews和imageview的创建。

我想要实现的是根据密钥创建不同的行。 一行可以包含文本和图像,而另一行只包含文本。我怎么能这样做?

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();
    }
}

2 个答案:

答案 0 :(得分:1)

覆盖此函数内的getViewTypeCount,返回要在listview中使用的类型视图的数量。

在其中覆盖getItemViewType(int position)编写逻辑以获取视图类型。

@Override
public int getViewTypeCount() {
   return 2; //return 2, in case you have two types of view
}

@Override
public int getItemViewType(int position) {
   return (contition) ? R.layout.layout1 : R.layout.layout2; //return 2, in case you have two types of view
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    convertView = (convertView == null) ?View.inflate(context, getItemViewType(position), null) : convertView;
    return convertView;
}

答案 1 :(得分:1)

为要为行覆盖不同的布局,您需要覆盖getViewItemTypegetViewTypeCount

您应该查看链接中的视频。

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;
}