Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridView elements changes their place dynamically when scroll screen

Tags:

android

i have a gridview layout, and all items are insert very fine,

now if I check on big screen then all work done is fine, because no scrolling is required

but if I check on small screen then items are changed their position dynamically,

bereif example is given below:-

like I have 28 items and arranged in a grid view 7*4, now if upto 20 items are shown in first screen, now remaining 8 is shown while i scroll screen down, but now some elements of first or second row is aslo put in last row.

code is here

public class ImageAdapter extends BaseAdapter
    {
        Context mContext;
        //public static final int ACTIVITY_CREATE = 10;
        public ImageAdapter(Context c)
        {
            mContext = c;
        }
        @Override
        public int getCount() 
        {
            // TODO Auto-generated method stub
            return providers.length;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            // TODO Auto-generated method stub
            View v;
            if(convertView==null)
            {
                LayoutInflater li = getLayoutInflater();
                v = li.inflate(R.layout.icontext, null);
                TextView tv = (TextView)v.findViewById(R.id.icon_text);
                tv.setText(providers[position]);
                ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
            iv.setImageResource(R.drawable.icon);
            }
            else
            {
                v = convertView;
            }
            return v;
        }
like image 795
DEVANG SHARMA Avatar asked May 19 '11 08:05

DEVANG SHARMA


2 Answers

You should change your getView method like this.

    public View getView(int position, View convertView, ViewGroup parent){
        // TODO Auto-generated method stub
        View v;
        if(convertView==null)
        {
            LayoutInflater li = getLayoutInflater();
            v = li.inflate(R.layout.icontext, null);
        }else{
            v = convertView;
        }
        TextView tv = (TextView)v.findViewById(R.id.icon_text);
        tv.setText(providers[position]);
        ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
        iv.setImageResource(R.drawable.icon);

        return v;
    }

Your problem is that when you use convertView it stores old data form the first records. Convert view is used to avoid layout inflation from resource which costs you time and memory. You should use the old inflated view, but set new data.

like image 113
Huds0nHawk Avatar answered Nov 02 '22 08:11

Huds0nHawk


I have just deleted the

if(convertView==null)

it works

like image 2
Boris Karloff Avatar answered Nov 02 '22 08:11

Boris Karloff