Android如何通过单击ImageView从ArrayAdapter获取id

时间:2011-11-11 10:09:38

标签: android

我在ArrayAdapter中放置了一个ImageView,列表如下:

Name1 | ImageView |

Name2 | ImageView |

Name3 | ImageView |

结束......

单击ImageView后,我不知道如何获取项目ID。

@Override
public View getView(int position, View contextView, ViewGroup parent) {
    final ViewHolder viewHolder;
    View rowView = contextView;
    final CardList list = _cardList.get(position);

    if (rowView == null) {
        LayoutInflater layoutInflater = _context.getLayoutInflater();
        rowView = layoutInflater.inflate(R.layout.cardlist_viewlist_tpl, null, true);
        viewHolder = new ViewHolder();
        viewHolder.tvCardListName = (TextView) rowView.findViewById(R.id.tvCardListName);
        viewHolder.btnCardListLearn = (ImageView) rowView.findViewById(R.id.btnCardListLearn);
        viewHolder.btnCardListLearn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(_context, LearningCardActivity.class);

                //!!!!!!!!!!!!!!!
                //this doesn't work, I always get 1st positon Id
                intent.putExtra(LearningCardActivity.CURRENT_CARD_LIST_ID, list.getId());
                //!!!!!!!!!!!!!!!!

                _context.startActivity(intent);
            }
        });

        rowView.setTag(viewHolder); 
    } else {
        viewHolder = (ViewHolder) rowView.getTag();
    }

    viewHolder.tvCardListName.setText(list.getName());

    return rowView;
}

2 个答案:

答案 0 :(得分:1)

您可以在ViewHolder类上添加一个属性,如:

static class ViewHolder {

   //...

   int position;

}

在返回视图之前设置此属性:

//...
viewHolder.position = position;
return rowView;

现在,您可以使用holder.position在侦听器上使用项ID。 在你的情况下,它应该是这样的:

//...
 intent.putExtra(LearningCardActivity.CURRENT_CARD_LIST_ID, holder.position);
//...

我不确定它是否是更好的方法,但它对我有用......

基于:http://www.itsalif.info/content/custom-list-views-icons-and-listeners-android#comment-6526

答案 1 :(得分:0)

您似乎正在重新使用rowView/contextView,并且如果rowView等于null,则只设置onClickListener。这基本上意味着viewholder对象上的侦听器将仅在第一次调用getView()时设置。因此,您将始终看到相同的第一个项目的ID。

如果要为每一行设置侦听器,则需要更改逻辑并移动setOnClickListener()调用。

public View getView(int position, View contextView, ViewGroup parent) {
    View rowView = contextView;
    if (rowView == null) {
        // Code here will only be run the very first time 
        // (when the row view hasn't been constructed yet)
    } else {
        // Code here will be run after that, since we're 
        // re-using the row's view
    }
}