1

这是我的适配器类:-

public class CustomAdapter extends BaseAdapter {

        Context c;

        CustomAdapter(Context c)
        {
            this.c=c;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return 3;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            final int pos=position;
            LayoutInflater inflater=LayoutInflater.from(c);
            View v=inflater.inflate(R.layout.layout_list_item, parent, false);
            ImageButton image_button=v.findViewById(R.id.imagebutton);
            image_button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Toast.makeText(c, "Image Button clicked:" + pos, Toast.LENGTH_SHORT).show();
                }
            });

            return v;
        }

    }

如何使所有图像按钮可点击?我尝试搜索答案,并根据此处给出的答案:如何在我尝试过的列表视图中使图像视图可点击,但只有我的第一行按钮是可点击的。请帮忙。

4

2 回答 2

1

在您的自定义适配器构造函数中

    LayoutInflater mInflater;  
    CustomAdapter(Context c)
    {
        mInflater = LayoutInflater.from(c); 
        // initialize inflater in the constructor.
        // need not initialize everytime getView is called.
    }

使用视图持有者

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

      static class ViewHolder
       {
           ImageButton ib;
       }
      @Override
      public View getView(int position, View item, ViewGroup parent) { 
       ViewHolder holder; 
       if(item == null){
       item = mInflater.inflate(R.layout.elementos_lista_temas, null);
       holder = new ViewHolder(); 
       holder.ib = (ImageButton) item.findViewById(R.id.imagebutton);
       item.setTag(holder);
       }
       else{
        holder = (ViewHolder)item.getTag();
       }
       return item;
       }

然后在你的活动课上

 ListView lv = (ListView) findViewById(R.id.listview);
 CustomAdapter cus = new CustomAdapter(this);
 lv.setAdapter(cus); 
 lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> listView, View itemView, int itemPosition, long itemId)
    {           
         Toast.makeText(ActivityName.this, "Image Button clicked:" + itemPosition, Toast.LENGTH_SHORT).show();
    }
    });
于 2013-06-27T04:45:44.457 回答
1

正如“ Listview-2010 的世界”所说,请参阅下面的链接显示如何在 android http://impressive-artworx.de/2011/list-all-installed-apps/中使用带有自定义 listview的 viewholder 类希望这对您有所帮助。

于 2013-06-27T04:45:50.553 回答