kuzdu kuzdu - 24 days ago 11
Android Question

Custom GridView has wrong position Android

I created a custom GridView. It works but the

i
shows the wrong position in the log.

The log output is
0,1,2,0
I would expect
0,1,2,3,4,5

In my GridView all elements are there but the titles and images wrong after the 3rd element.

When I tap the elements I get the right index.

I'm new in Android. Is there a cache or do I have to clean the GridView? I found a lot of similar threads but no one could help. If you need more code please let me know.

public View getView(int i, View convertView, ViewGroup parent) {
View gridViewAndroid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


if (convertView == null) {

gridViewAndroid = new View(mContext);
gridViewAndroid = inflater.inflate(R.layout.course, null);

TextView textViewAndroid = (TextView) gridViewAndroid.findViewById(R.id.android_gridview_text);
ImageView imageViewAndroid = (ImageView) gridViewAndroid.findViewById(R.id.android_gridview_image);

String url = "xxx/" + courses.get(i).getImageName();
Picasso.with(mContext).load(url).into(imageViewAndroid);
Log.d("IMAGE", "i" + i);
textViewAndroid.setText(courses.get(i).getName());
} else {
gridViewAndroid = (View) convertView;
}

return gridViewAndroid;
}

Answer Source

Your views are recycled ,thats why this problem happening. try below code

Add a view holder inside your adapter

static class ViewHolder {
     TextView textViewAndroid;
     ImageView imageViewAndroid;
}

Change your getView() to below code

public View getView(int i, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if (convertView == null) {   
         LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

         convertView = inflater.inflate(R.layout.course, null);
         holder = new ViewHolder();
         holder.textViewAndroid = (TextView) convertView.findViewById(R.id.android_gridview_text);

         holder.imageViewAndroid = (ImageView) convertView.findViewById(R.id.android_gridview_image);
         convertView.setTag(holder);
    } else {
         holder = (ViewHolder) convertView.getTag();
    }

   String url = "xxx/" + courses.get(i).getImageName();
   Picasso.with(mContext).load(url).into(holder.imageViewAndroid);
   Log.d("IMAGE", "i" + i);
   holder.textViewAndroid.setText(courses.get(i).getName());
   return convertView;
}

Put the static class inside your public class X extends BaseAdapter