GridView and icon clutter when using "if (convertView == null)"

I am new to this area, so pls be patient :)

I am using some LayoutInflater to set the GridView with the + icon below. When I use, as shown below, everything goes well. But when I remove the comment mark “//”, everything is messy. Icons are presented in the wrong order, and they even double in several places.

View v; // if (convertView == null) { // if it not recycled, initialize some attributes LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(R.layout.icon, null); TextView tv = (TextView)v.findViewById(R.id.icon_text); tv.setText(kraj[position]); ImageView iv = (ImageView)v.findViewById(R.id.icon_image); iv.setImageResource(mThumbIds[position]); iv.setScaleType(ImageView.ScaleType.CENTER_CROP); iv.setLayoutParams(new LinearLayout.LayoutParams(mniejszy, mniejszy)); // } else { // v = (View) convertView; // } return v; 

This is a tutorial in which I got a piece of code: http://developer.android.com/guide/topics/ui/layout/gridview.html

+4
source share
2 answers

This is because you only install the image when the convertView is null (this will happen, for example, when the GridView first displayed on the screen), and as the GridView scrolls (the convertView will not be empty), it will recycle the row views, so you get the old rows that you have not updated with new images / text. Your code should look like this:

 View v; if (convertView == null) { // if it not recycled, initialize some attributes LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(R.layout.icon, null); } else { v = (View) convertView; } TextView tv = (TextView)v.findViewById(R.id.icon_text); tv.setText(kraj[position]); ImageView iv = (ImageView)v.findViewById(R.id.icon_image); iv.setImageResource(mThumbIds[position]); iv.setScaleType(ImageView.ScaleType.CENTER_CROP); iv.setLayoutParams(new LinearLayout.LayoutParams(mniejszy, mniejszy)); return v; 
+2
source

What you are experiencing is probably due to the fact that the recycled view has data that you previously assigned.

Please see below code for directions.

 View v; if(convertView == null) { LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(R.layout.icon, null); } else { v = (View) convertView; } // now override whatever `recycled view` has TextView tv = (TextView)v.findViewById(R.id.icon_text); tv.setText(kraj[position]); ImageView iv = (ImageView)v.findViewById(R.id.icon_image); iv.setImageResource(mThumbIds[position]); iv.setScaleType(ImageView.ScaleType.CENTER_CROP); iv.setLayoutParams(new LinearLayout.LayoutParams(mniejszy, mniejszy)); return v; 
+1
source

All Articles