Search code examples
androidgridviewonlongclicklistener

How come that views get selected randomly in my GridView?


I have got a Gridview in my app. I then added a OnItemLongClickListener to that GridView. Check out this code:

myGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                int position, long id) {

            view.setBackgroundResource(R.drawable.image_border);
            return true;
        }

    });

Now, all I want to do is set a border to an image in my gridview. The problem with my code is that it sets the border to an image but when I start scrolling up and down, suddenly an other image has got the border although it was never clicked.

How come that the border gets set to other images as well. Any idea how I can fix this?


Solution

  • Your Adapter class does this internally to reduce memory consumption and to efficiently use device resources.

    In your Adapter class you should do

    public View getView (int position, View convertView, ViewGroup parent){
        // convertView is reused from previously scrolled out view to reduce memory consumption
        if( convertView == null ){
            //We must create a View:
            convertView = inflater.inflate(R.layout.my_list_item, parent, false);
        }
        // Set border to the image if it is selected otherwise set it to default
        // keep in mind when you add any condition here, else should also be addressed
        return convertView;
    }