Help regarding onClick() event on an item of ListView custom row layout

I have a ListView whose rows are formatted by me. Each row has a mix of ImageView and TextView. I have also implemented my own adapter and am able to draw each row through it.

Now, I would want something like this-

  • User clicks on an ImageView (not anywhere else on the row, but only this ImageView should respond to clicks)
  • I get to know the position of the row whose ImageView was clicked.

I have tried many things for this and have wanted my code to be as efficient as possible (in terms of overkill). Currently i can capture the click event on that particular ImageView only, but I can't know which row was clicked.

I have provided an attribute in the Row XML like this-

<ImageView android:id="@+id/user_image"
    android:padding="5dip" 
    android:layout_height="60dip" 
    android:layout_width="60dip"
    android:clickable="true"
    android:onClick="uImgClickHandler"/> 

And in my code, I have a method like this:

public void uImgClickHandler(View v){
  Log.d("IMG CLICKED", ""+v.getId());
  LinearLayout parentRow = (LinearLayout)v.getParent();

 }

I can get the parent row (perhaps) but am not sure how to go further from here. Can someone please help?


Please refer this,
Me just writing the code to give you idea, Not in correct format

 class youaddaper extends BaseAdapter{

   public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater inflate = LayoutInflater.from(context);
        View v = inflate.inflate(id, parent, false);

      ImageView imageview = (ImageView) v.findViewById(R.id.imageView);
        imageview.setOnClickListener(new imageViewClickListener(position));
      //you can pass what ever to this class you want,
      //i mean, you can use array(postion) as per the logic you need to implement 
   }
   class imageViewClickListener implements OnClickListener {
   int position;
    public imageViewClickListener( int pos)
        {
            this.position = pos;
        }

    public void onClick(View v) {
      {// you can write the code what happens for the that click and 
       // you will get the selected row index in position
     }
}

}

Hope it helped you


Another option is to use the methods setTag() and getTag() of the view. You set it in your getView like this:

imageView.setTag(new Integer(position));

Then in the onClick() you can find the tag by:

Integer tag = v.getTag();

This will then be used to correlate the image view to the position of the listview item.

Note that this approach will give problems if the listview can lose items from the middle, so that the item positions change during the lifetime of the listview.