ListView Scrolling Issue: on Item Selection

后端 未结 2 1868
悲哀的现实
悲哀的现实 2021-01-25 21:26

I have Listview with which I\'m trying to display my custom Adapter.Everything works fine except when I select list item and scroll it,the items which were not selected are alre

2条回答
  •  梦毁少年i
    2021-01-25 21:42

    v.setBackgroundColor(Color.parseColor("#88dfdf")); You should not only do that but also have an ArrayList selectedList in which you 'remember' if the item is selected. Then in getView you should 'inspect' that list and put the color accordingly.

     if ( selectedList.get(position) )
          convertView.setBackgroundColor(Color.parseColor("#88dfdf"));
     else      
          convertView.setBackgroundColor(Color.parseColor( normal color ));
    

    Initializing the list in the adapter class:

    ArrayList selectedList = new ArrayList();
    
    public CustomAdapter(Context context, List mList)
    {
     .........
     int nr = -1;
     while (++nr < mList.size() )
        selectedList.add(false);
     }
    }
    

    also add this to getView() function

       public View getView(final int position, View convertView, ViewGroup parent)
        { ...............................
            holder.contact_img.setImageBitmap(ImageHelper.getRoundedCornerBitmap(scaleBitmap, 100));
    
            if(selectedList.get(position)== true)
            {
              convertView.setBackgroundColor(Color.parseColor("#88dfdf")); 
            }   
            else
            {
              convertView.setBackgroundColor(Color.background_light); 
            }
            return convertView;
        }
    

    also add the following line to your onListItemClick().

    protected void onListItemClick(ListView l, View v, int position, long id) 
    {
        ..................
        if(mArrayAdapter.selectedList.get(position)==true)
        {
          v.setBackgroundColor(Color.background_light));
          mArrayAdapter.selectedList.set(position,false);
        }
        else
        {
          v.setBackgroundColor(Color.parseColor("#88dfdf"));
          mArrayAdapter.selectedList.set(position,true);
          Toast.makeText(getApplicationContext(), "Items Pos: " + position +"and Name : "+ name, 0).show();
        }
    
    }
    

    and also make selectedList variable to public in CustomAdapter.

提交回复
热议问题