Search code examples
androidandroid-listviewlistenerandroid-adapterandroid-adapterview

Android: On click in adapter give wrong position


I am developing an application in which i am having a list view with custom adapter. I am attaching the ArrayList to the custom adapter. The adapter is having four image view, and onclick listener is applied to each image view in get view.

I am populating the array list from other two arraylist on the basis of condition as :

/* Condition 1 */
for(int i = 0; i <  arrayList.size(); i++){
    if( a == id){
        arrayList1.add(arrayListOther.get(i));
    }
}

/* condition 2  */
for(int i = 0; i <  arrayList.size(); i++){
    arrayList1.add(arrayList.get(i));
}

When my arrayList one populates only from condition 2 then on click of 1st item of list the position it gives is 0. But when my arraList populates from condtion 1 and 2 both that time 1st item is populated from arrayListOther and rest from arrayList from condition two, that time on click of 1st item on list, it gives position as 1.

In my Adapter:

public class ViewHolder {
    ImageView image1;
    ImageView image2;
    ImageView image3;
    ImageView image4;
}

public View getView(final int position, View view, ViewGroup parent) {
    if (view == null || view.getTag() == null) {
        holder = new ViewHolder();
        view = inflater.inflate(R.layout.listview_adapter_layout, null);

        holder.image1 = (ImageView) view.findViewById(R.id.imageView1);
        holder.image2 = (ImageView) view.findViewById(R.id.imageView2);
        holder.image3 = (ImageView) view.findViewById(R.id.imageView3);
        holder.image4 = (ImageView) view.findViewById(R.id.imageView4);

        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }        

    // Some code here   
    // Also having Async task     

    if(flag == 2){
        holder.image1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {        
                // Also having Async task
                Log.d("Position",""+position);
            }    
        });
    }

    // Some code here
}

What is wrong in this i am not getting. Please suggest me what should i do.


Solution

  • Add tag to imageview like below :

            holder.image1 = (ImageView) view.findViewById(R.id.imageView1);
            holder.image2 = (ImageView) view.findViewById(R.id.imageView2);
            holder.image3 = (ImageView) view.findViewById(R.id.imageView3);
            holder.image4 = (ImageView) view.findViewById(R.id.imageView4);  
            holder.image1.setTag(position);
    
      holder.image1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {        
                // Also having Async task
                  Integer index = (Integer) v.getTag();
            }
        });