如何在侦听器内传递适配器的信息。

时间:2014-03-21 04:16:48

标签: java android adapter onclicklistener

int" pos"没有正确传递。 ImageViewOnClick()时如何更正值。 似乎listener激活信息不再准确。

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder vHolder;
    if (convertView != null)
        vHolder = (ViewHolder) convertView.getTag();
    else {
        convertView = mInflater.inflate(R.layout.car_list, null);
        vHolder = new ViewHolder();
        vHolder.textView = ((TextView) convertView.findViewById(R.id.tvCarListText));
        vHolder.textView2 = ((TextView) convertView.findViewById(R.id.tvCarDescriptionListText));
        vHolder.imageView = ((ImageView) convertView.findViewById(R.id.ivCarListMenuIcon));
        vHolder.relativeLayout = ((RelativeLayout) convertView.findViewById(R.id.relativeLayout));
        convertView.setTag(vHolder);


        CarItem c = mItems.get(position);
        final int pos = (int)c.getCarID();

        vHolder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCarEditDialog(pos); //THIS IS PASSING WRONG <--------------
            }
        });
    }
    return convertView;
}

2 个答案:

答案 0 :(得分:1)

使用ImageView.setTag()获取ImageVIew上单击行的位置,然后单击为:

vHolder.imageView.setTag(pos);  // set current pos
vHolder.imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        showCarEditDialog(Integer.parseInt(v.getTag().toString()));
    }
});

答案 1 :(得分:0)

你可以这样轻松地做到这一点:

    public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder vHolder;
    if (convertView != null)
        vHolder = (ViewHolder) convertView.getTag();
    else {
        convertView = mInflater.inflate(R.layout.car_list, null);
        vHolder = new ViewHolder();
        vHolder.textView = ((TextView) convertView.findViewById(R.id.tvCarListText));
        vHolder.textView2 = ((TextView) convertView.findViewById(R.id.tvCarDescriptionListText));
        vHolder.imageView = ((ImageView) convertView.findViewById(R.id.ivCarListMenuIcon));
        vHolder.relativeLayout = ((RelativeLayout) convertView.findViewById(R.id.relativeLayout));
        convertView.setTag(vHolder);


    }

        vHolder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showCarEditDialog((int)((CarItem)mItems.get(position)).getCarId);
            }
        });

    return convertView;
}