如何将自定义视图添加到列表适配器

时间:2011-08-19 10:34:34

标签: android listview

我有一个listview,它是由自定义listadapter创建的。在这个列表视图中,我希望listview的每个项目都有一个文本和一个视图。我能够添加文本。我的视图是一个自定义视图的视图.it没有添加。我不知道为什么?有人想帮忙吗?

private class ItemsAdapter extends BaseAdapter{
    String[] items;
    Context context;
    public ItemsAdapter(Context context,String[] items){
        this.items=items;
        this.context=context;
    }

    public View getView(final int position,View convertView,ViewGroup Parent){
        TextView itemText;
        View image;
        View view=convertView;
        if(view==null){
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.listitem, null);
        }

        itemText=(TextView) view.findViewById(R.id.label);
         itemText.setText(items[position]);

        image=new SampleView(context);
        LinearLayout ln1=(LinearLayout)view.findViewById(R.id.ll1);


        ln1.addView(image,1);
         return view;
    }
    public int getCount() {
           return items.length;
          }

          public Object getItem(int position) {
           return position;
          }

          public long getItemId(int position) {
           return position;
          }
}

1 个答案:

答案 0 :(得分:0)

试试这样:

private class ItemsAdapter extends BaseAdapter{
    String[] items;
    Context context;
    public ItemsAdapter(Context context,String[] items){
        this.items=items;
        this.context=context;
    }

    public View getView(final int position,View convertView,ViewGroup Parent){
       ViewHolder holder = new ViewHolder();
        if(convertView==null){
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.listitem, null);


        }
        holder.itemText=(TextView) converView.findViewById(R.id.label);
        holder.itemText.setText(items[position]);

        holder.image=new SampleView(context);
        LinearLayout ln1=(LinearLayout)convertView.findViewById(R.id.ll1);


        ln1.addView(holder.image,1);
        return convertView;
    }
    public int getCount() {
           return items.length;
          }

          public Object getItem(int position) {
           return position;
          }

          public long getItemId(int position) {
           return position;
          }

     class ViewHolder {
            TextView itemText;
            View image;
     }
}