Skip to content Skip to sidebar Skip to footer

How To Show The Selected Item In ListView (Android)

The problem is when the ListView loses focus, the selected item isn't highlighted. I use a custom ArrayAdapter which uses the following layout for items:

Solution 1:

i guess you have created array adapter in the following manner. if i am correct use the following:

static final String[] color = new String[]{"red","green","blue"};

We need to use the setListAdapter(..) method of the ListActivity class to bid the two (data and view). Android provides many implementations of the ListAdapter. We will use the simple ArrayAdapter.

What does the ArrayAdapter expect?

It expects the context object, the row layout and the data in an array.

So here it is:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, PENS));
    getListView().setTextFilterEnabled(true);       
  }

use below code to show selected item

protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Object o = this.getListAdapter().getItem(position);
    String pen = o.toString();
    Toast.makeText(this, "You have chosen the color: " + " " + color, Toast.LENGTH_LONG).show();
}

Solution 2:

The simplest way is to add android:background="?android:attr/activatedBackgroundIndicator" in the layout you use for the row


Post a Comment for "How To Show The Selected Item In ListView (Android)"