ListView selection issue...Using onItemClick(AdapterView<?> parent, View view, ...)

10,823

You'll have to override getView() in a subclass of ListAdapter, in this case, ArrayAdapter.

This is because Android actually reuses rows to conserve resources and CPU (when a row is scrolled off the screen, it is reused for new rows that come into view). So, if you set the background grey on one row, it'll probably end up being used again, and the background will still be grey.

If you subclass ArrayAdapter, you can have your onItemClickListener set some sort of flag, and then your ArrayAdapter's getView(), you can set the appropriate background color based on the flag.

This link has an example of subclassing ArrayAdapter

Share:
10,823
searchMaker
Author by

searchMaker

Updated on June 04, 2022

Comments

  • searchMaker
    searchMaker almost 2 years

    The problem I hope to resolve here is that when I click on one item in the ListView that item's background changes to light gray, but when I continue to scroll through the list every 4th item has the background changed to light gray even though those other items have not been clicked. How do I make only the item I clicked be effected by the click?

        ListView lv = (ListView) findViewById(R.id.resultsList);
        lv.setAdapter(new ArrayAdapter<String>(this, R.layout.resultitem, (String[])labelList.toArray(new String[labelList.size()])));
    
        lv.setOnItemClickListener(new OnItemClickListener() {    
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {      
                TextView tv = (TextView)view.findViewById(R.id.result);
                tv.setBackgroundColor(Color.LTGRAY);
                tv.setTextColor(Color.BLACK);
            }
         }
    
  • searchMaker
    searchMaker about 14 years
    Is there something wrong here? private class LabelAdapter extends ArrayAdapter<String> { private String[] items; public LabelAdapter(Context context, int textViewResourceId, String[] strings) { super(context, textViewResourceId, strings); this.items = strings; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; TextView tt = (TextView) v.findViewById(R.id.result); tt.setText(items[position]); return v; } }
  • searchMaker
    searchMaker about 14 years
    So there really is no simple way to stop the adapter from reusing views?