KaHeL KaHeL - 2 years ago 214
Android Question

Change background color of selected item on a ListView

I want to know on how I can change the background color of the selected item on my listView. I only want to change the specific item clicked by the user, meaning if the user clicks another item it will be the one which is highlighted. Well since I want it to keep simple as possible and use the default android listview I used this code instead:

record_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
for (int ctr=0;ctr<=record_items.length;ctr++){
catch (Exception e){
Log.v("Selected item",record_list.getItemAtPosition(i));

Ok this one is working but the problem is that it's slow. Now I want to know if there's any other way around that I can do which will give the same output as I made.

I tried using
but it gives me a null pointer exception.

I also tried the selector.xml but it also didn't do the trick.
Furthermore, there is one properties here on ListView which is called listSelector. It's a drawable as said by the documentation "Drawable used to indicate the currently selected item in the list." I also believe that this should do the trick and yes it do the trick on my emulator but not on my galaxy tab. I also tried the other methods but nothing works as I wanted it to be.

Answer Source

You can keep track the position of the current selected element:

    OnItemClickListener listViewOnItemClick = new OnItemClickListener() {

        public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
                mSelectedItem = position;

And override the getView method of your adapter:

    public View getView(int position, View convertView, ViewGroup parent) {
        final View view = View.inflate(context, R.layout.item_list, null);

        if (position == mSelectedItem) {
            // set your color

        return view;

For me it did the trick.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download