我已经在List行中实现了自定义适配器并具有多个视图(ImageView,TextView)。我想在每个上面设置监听器。
这就是我所做的
if (containerRow == null) {
viewHolder.item.setOnClickListener(new OnImageViewClickListener(position, context, viewHolder));
}
现在这给了我在OnImageViewClickListener中的错误位置,因为viewHolder.item.setOnClickListener只在(containerRow == null)时被调用一次。如果我在其他部分执行此操作,而不是为多个项目(ImageView,TextView)创建多个侦听器对象以及该行数(我是否正确?)
根据我的理解,我无法实现这一点是在ListView的setOnItemClickListener中,因为我无法获取用户点击的项目。
请建议我在这些行项目上实现监听器并获得正确位置的一些巧妙方法。
答案 0 :(得分:1)
将位置设置为每个视图的TAG,并在每个可单击视图上设置侦听器
将侦听器定义为内部类,并从视图中获取标记
if (containerRow == null) {
....
....
viewHolder.txv.setOnClickListener(clickListener);
viewHolder.img.setOnClickListener(clickListener);
.....
.....
}else{
viewHolder = containerRow.getTag();
}
viewHolder.txv.setTag(position);
viewHolder.img.setTag(position);
OnClickListener:
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
// you have the correct position
switch(v.getId()){
......
......
}
}
};
答案 1 :(得分:1)
这似乎适用于ListItem是包含列表项数据的POJO ......
public class ListItemAdapter extends ArrayAdapter<ListItem>
{
private static final String TAG = "ListItemAdapter";
private Activity mContext;
private int mLayoutResourceId;
private List<ListItem> mItems = null;
static class ViewHolder
{
public TextView text1;
public TextView text2;
public ImageView image;
}
public ListItemAdapter(Activity context, int textViewResourceId, List<ListItem> items)
{
super(context, textViewResourceId, items);
mContext = context;
mLayoutResourceId = textViewResourceId;
mItems = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater inflater = mContext.getLayoutInflater();
v = inflater.inflate(mLayoutResourceId, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.text1 = (TextView) v.findViewById(android.R.id.text1);
viewHolder.text1.setOnClickListener(new ItemClickListener(position));
viewHolder.text2 = (TextView) v.findViewById(android.R.id.text2);
viewHolder.text2.setOnClickListener(new ItemClickListener(position));
viewHolder.image = (ImageView) v.findViewById(android.R.id.icon);
viewHolder.image.setOnClickListener(new ItemClickListener(position));
v.setTag(viewHolder);
}
ListItem item = mItems.get(position);
Log.v(TAG, item.toString());
ViewHolder holder = (ViewHolder) v.getTag();
String text = item.getText1();
holder.text1.setText(text);
text = item.getText2();
holder.text2.setText(text);
Drawable img = item.getImage();
Log.v(TAG, "image : " + img);
holder.image.setImageDrawable(img);
return v;
}
class ItemClickListener implements View.OnClickListener
{
int position;
public ItemClickListener(int pos)
{
this.position = pos;
}
public void onClick(View v)
{
Toast.makeText(mContext, "Item clicked in row - " + position, Toast.LENGTH_SHORT).show();
};
}
}