ListView Scrolling Issue: on Item Selection

﹥>﹥吖頭↗ 提交于 2019-12-02 13:43:01
greenapps

v.setBackgroundColor(Color.parseColor("#88dfdf")); You should not only do that but also have an ArrayList<Boolean> 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<Boolean> selectedList = new ArrayList<Boolean>();

public CustomAdapter(Context context, List<Contacts> 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.

Another solution, put a simple int in your Custom list View

public class CustomListView extends BaseAdapter {
     private int selected = 0;

check the position in your getView

public View getView(int position, View convertView, ViewGroup parent) {
   if (position == selected)
        selector.setImageResource(R.drawable.selected);
   else
        selector.setImageResource(R.drawable.not_selected);

and finally in the clickListener of your activity or fragment, set the position with setter/getter method and notify the adapter.

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    customListViewAdapter.setSelectedPosition(position);
    customListViewAdapter.notifyDataSetChanged();
}

It works like a charm for me ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!