ralph ralph - 17 days ago 6
Android Question

setOnItemClickListener in ListView affecting multiple rows

I have a custom listview and a custom adapter.
When clicking a row of this listview, the text of a TextView is set to white and the background of this row is set to black.

All is well but when clicking a row, other rows are having a background color set to Black too and when scrolling up and down all will mess up.

getView() in custom adapter

public View getView(final int position, View convertView, ViewGroup parent) {
final ListItem holder;
View vi=convertView;

if(vi==null){
vi = inflater.inflate(R.layout.list, null);
holder = new ListItem();
holder.nametext= (TextView) vi.findViewById(R.id.name);
vi.setTag(holder);

}else{
holder = (ListItem) vi.getTag();
}

holder.nametext.setText(""+item.name);
return vi;
}


In mainactivity:

CustomAdapter listadapter = new CustomAdapter(context, R.layout.list, items);
list.setAdapter(listadapter);

list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg){
TextView v = (TextView) view.findViewById(R.id.name);
view.setBackgroundColor(Color.BLACK);
v.setTextColor(Color.WHITE);
}

});


I tried puttin the setOnItemClickListener in the getView() but no luck either..

Any help? thanks.

Answer

Custom listviews "create" a view for the showing rows only, when scrolling down the next showing row will be affected like the first one..

To prevent this issue, you need to create a boolean field in ListItem Clicked;

Then when clicking the view, the item.Clicked is set to true where in getView()

final ListItem item = items.get(position);   

and

List<ListItem> items;

as your adapter's variable

The implementation:

You need to set the setOnClickListener in your getView() as below

vi.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg1) {

            if(previousView!=null){
                ListItem previousItem = items.get(previousPosition);
                previousItem.Clicked = false;
            }

            item.Clicked = true;
            previousView = arg1;
            previousPosition = position;
            notifyDataSetChanged();
        }

    });



    if(!item.isClicked){
        holder.nametext.setTextColor(Color.BLACK);
        vi.setBackgroundColor(Color.WHITE);
    }else{
        holder.nametext.setTextColor(Color.WHITE);
        vi.setBackgroundColor(Color.BLACK);
    }

});