Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

android - How to change background color of selected items in ListView?

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 that's checked on selected items. And i'm having trouble understanding how to do it from those codes.

I am following a tutorial found Here, and that's preaty much how my code looks only different names.

I Want to have a multipile selection ListView, when an item selected the background color is changed to mark the items i've selected.

Maybe i can acomplish this using a custom selector? I understood the common way is to save the positions of selected and do something in the getView function. I saw people creating ViewHolder, but i didn't really understand what it has to do with anything. Can someone please help me?

Thank in advance, Eric

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well i finally solved it, hope this helps someone :

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

In my Adapter i define:

public ArrayList<Integer> selectedIds = new ArrayList<Integer>();

With the following method :

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


    }
    else
    {
        selectedIds.add(position);
    }
}

which addes emoves 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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...