How to change background color of selected items in ListView?

后端 未结 3 962
情深已故
情深已故 2020-12-04 02:26

i\'ve seen many simillar questions and every answer is very specific to the problem and no straight forward answer, or i found tutorials that show how to create a checkbox t

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 03:10

    Well i finally solved it, hope this helps someone :

    What i did was created an ArrayList that stores all the position of selected items, and toggle the background colors on clicks.

    In my Adapter i define:

    public ArrayList selectedIds = new ArrayList();
    

    With the following method :

        public void toggleSelected(Integer position)
    {
        if(selectedIds.contains(position))
        {
            selectedIds.remove(position);
    
    
        }
        else
        {
            selectedIds.add(position);
        }
    }
    

    which addes\removes items from the ArrayList

    In my getView method :

                if (selectedIds.contains(position)) {
                convertView.setSelected(true);
                convertView.setPressed(true);
                convertView.setBackgroundColor(Color.parseColor("#FF9912"));
            }
            else
            {
                convertView.setSelected(false);
                convertView.setPressed(false);
                convertView.setBackgroundColor(Color.parseColor("#000000"));
            }
    

    This checks if the position is storred in the ArrayList. if it does, paint it as selected. if not, the opposite.

    all is left is the OnItemClick listener, i added :

        ((YourAdapter)list.getAdapter()).toggleSelected(new Integer(position));
    

    When YourAdapter is the adapter of your ListView

    Hope this helps anyone, as it's a generic answer :)

提交回复
热议问题