这是我的适配器类:
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;
}
}
如何使所有图像按钮都可单击?我尝试搜索答案,并按照此处给出的答案进行操作:how to make an imageview clickable in an listview我尝试过,但是只有第一行按钮是可单击的。请帮忙。
最佳答案
在您的自定义适配器构造函数中
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();
}
});