Unable to "unselect" list item

I managed to get the background change of an individual list item in setOnItemClickListener using

view.setBackgroundResource(R.color.green); 

I only need one selected at a time, so when I clicked on other elements of the list, I tried lv.invalidate()and lv.getChildAt(0).invalidate()but did not work, and the second caused a null pointer exception. Any ideas on color return?

+3
source share
5 answers

I am making several split-screen files, and the xml selectors do not work. To set the color back, I ended up saving the view that was clicked in View currentlySelectedViewand setting a transparent background when I clicked on another view.

currentlySelectedView.setBackgroundResource(R.color.transparent);
+2
source

, . , , . .

           

Android ListView

+1

" ", , , . ListView, () (unhighlight) .

//you can extend whatever kind of adapter you want
public class AutoSelectingListViewAdapter extends ArrayAdapter<Thingy>{

    private LayoutInflater inflater;

    public boolean shouldHighlight = false;
    public int highlightIndex = -1;

    public AutoSelectingListViewAdapter(Context context, int resourceId, List<Thingy> objects) {
        super(context, resourceId, objects);
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        ItemHolder holder = null;

        if (convertView == null){
            // always recycle!
            holder = new ItemHolder();
            convertView = inflater.inflate(R.layout.custom_list_item, null);
            holder.clue = (TextView) convertView.findViewById(R.id.custom_list_item_text);
            convertView.setTag(holder);
        }else{
            holder = (ItemHolder) convertView.getTag();

        }
            // fake highlighting!
        if (shouldHighlight && highlightIndex == position){
            convertView.setBackgroundColor(0xffb5bfcc); // put your highlight color here

        }else{
            convertView.setBackgroundColor(0x00000000);  // transparent

        }

        Thingy thingy = this.getItem(position);

        holder.clue.setText(thingy.textData);
        return convertView;

    }
    class ItemHolder{

        TextView text;
        // any other views you need here

    }




}

, , :

targetListView.setSelection(4); // give item 4 focus
AutoSelectingListViewAdapter myAdapter = (AutoSelectingListViewAdapter) targetListView.getAdapter();
myAdapter.highlightIndex = 4; // highlight item 4
myAdapter.shouldHighlight = true;
myAdapter.notifyDataSetChanged(); // force listview to redraw itself

:

myAdapter.shouldHighlight = false;
myAdapter.notifyDataSetChanged();
0

OnItemClickListener.onItemClick :

adapter.notifyDataSetInvalidated();
0

All Articles