Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I had exactly the same problem. I haven't found a way how to do this in XML, but I have found a workaround in code. The following code is tested in application that supports API level 7+</p> <p>First, you need to alter the adapter for the <code>ListView</code> a bit:</p> <pre><code>public class ListViewAdapter extends BaseAdapter { private int selectedItemPosition = -1; // your code public void selectItem(int i) { selectedItemPosition = i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { // your code if (i == selectedItemPosition) { // set the desired background color textView.setBackgroundColor(context.getResources().getColor(R.color.highlight)); } else { // set the default (not selected) background color to a transparent color (or any other) textView.setBackgroundColor(Color.TRANSPARENT); } return view; } } </code></pre> <p>Next you have to inform the adapter that the selection changed in your <code>OnItemClickListener</code>'s <code>onItemClickMethod</code>:</p> <pre><code>@Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // select the item ((ListViewAdapter) listview.getAdapter()).selectItem(position); // force redraw of the listview (invalidating just "view" is not enough) ((ListView) parent).invalidateViews(); // your code } </code></pre> <p>That should be it. Now whenever you wan't to change the selected item you can use the same code that is used in <code>onItemClick()</code>, ie. <code>selectItem()</code> followed by <code>invalidateViews()</code>. Instead of calling <code>invalidateViews()</code>, the adapter's <code>notifyDataSetChanged()</code> can also be used.</p> <p>Also you should also add an appropriate listSelector to the list view, to avoid the brief flicker of the default selector when the item is clicked. However there's a bug with list selectors on API 7 and 8 when the background of the whole view is changed. You can find a workaround <a href="https://stackoverflow.com/a/10490435/1096429" title="here">here</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload