Android - setSelected in OnItemClick in ListView

dropsOfJupiter picture dropsOfJupiter · Jan 26, 2011 · Viewed 15.9k times · Source

I am trying to set item selected in OnItemClick event in ListView and it just wouldn't leave item selected. What am I doing wrong?

lView.setOnItemClickListener(new OnItemClickListener()
   {
    @Override
    public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View clickedview, int position, long id)
    {
     clickedview.setSelected(true); 
        mItemsAdapter.select(position);
    }
   }); 

few things:
1. I am trying to implement Multiple Select on the list View.
2. I cannot extend from ListActivity because Activity extends from BaseActivity custom class already.
3. mItemsAdapter is a custom ItemsAdapter adapter that extends BaseAdapter.
4. I don't need a checkbox in there, just to be able to see the row selected is fine.
5. ItemsAdapter overrides getView() and sets the layout of the row by inflating xml

Answer

Leandro picture Leandro · Jul 18, 2012

I could manage to get an item of a ListView to be set as selected when long-clicked:

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
        int position, long id) {
    parent.requestFocusFromTouch(); // IMPORTANT!
    parent.setSelection(position);
    return true;
}

It only worked after I called requestFocusFromTouch().