TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Detecting if item is checked inside of getView() in a adapter

When a listView row is pressed, I do this : listView.setItemChecked(position, value). This changes the background color with a selector to show the position is active.

I also do basic zebra stripes in my adapter's getView() method. Like this:

if (pos % 2 == 1) {
    convertView.setBackgroundColor(Color.parseColor("#99DEEAF1"));
} else if (viewType != 0) {
    convertView.setBackgroundColor(Color.parseColor("#00000000"));
}

Now in this getView() method, I'd like to know if my item (in the current position) is checked so that I don't try to change the background color (as seen above) and override my selector for my listView. Is this possible?

In the end I want to add a clause to the if statement that don't do either one if item is checked.

Upvotes: 0

Views: 644

Answers (2)

Goran Horia Mihail
Goran Horia Mihail

Reputation: 3645

You could use a helper class like this to remember the selected postion:

public class ListChoice
{
    private int selection;

    public void setListChoice(int s)
    {
        selection = s;
    }

    public int getListChoice()
    {
        return selection;
    }
}

then:

listView.setItemChecked(position, value);
ListChoice lc = new ListChoice();
lc.setListChoice(position);

and in getView()

if(pos != lc.getListChoice())
{
    if (pos % 2 == 1) 
    {
        convertView.setBackgroundColor(Color.parseColor("#99DEEAF1"));
    } 
    else if (viewType != 0) 
    {
        convertView.setBackgroundColor(Color.parseColor("#00000000"));
    }
}

Upvotes: 1

Amit Gupta
Amit Gupta

Reputation: 8939

You can create a Model class which take care wether a list item is checked or not inside getView() method.

OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            //Update the model here
        }
    };

For help go through this link

Upvotes: 0

Related Questions