Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: setting a programatically clicked listview item to the selected state

In my application I have a left pane that contains a list view. The selection made in this list view, then calls for the relevant data, which updates the right pane, and other links and elements in the activity. Because of this design, the left pane must always have a selection made in order to give the rest of the activity useful values.

In the onCreate method of my activity I call the following in order to select the first element in the list by default. (programList is my listview)

programList.performItemClick(programList, 0, programList.getItemIdAtPosition(0);

That all works great and the view loads as expected with the right values, except for one thing.

I have added a drawable selector for the listview which highlights the selected element. When the item is physically clicked in the emulator it will highlight (I am using CHOICE_MODE_SINGLE), but it does not highlight upon calling performItemClick(). I've looked around for help on stackoverflow and tried to use the following before the click, but it did not make a difference.

    programList.requestFocusFromTouch();
    programList.setSelection(0);

From reading the API it sounds like the setSelection method does not set the state of the item under a touch interface, and from my results it seems that the performItemClick method does not either. I also tried to use

    programList.getAdapter().getView(0, null, null).setSelected(true);

Then I can read the state of the text view and see that it is selected, but that also did nothing to change what is displayed on the screen.

Is there something in the onCreateMethod that is preventing the state of the button from being drawn differently? I tried invalidating the drawable inside the individual text view and invalidating the text view itself, but that did not help. I also tried changing the background of the text view, but it appears that the selector that I've set governs that or is drawn in front. I know that I have the correct textView because I've used getText to read what's inside.

If anyone is able to help me with this problem or point me towards a solution, it would be greatly appreciated.

like image 873
ndw Avatar asked Oct 12 '12 22:10

ndw


1 Answers

The trick is to override the getView() method of the adapter. Try this:

@Override
public View getView(int position, View convertView, ViewGroup parent ) {
    final View renderer = super.getView(position, convertView, parent);
    if (position == index_of_selected_item) {
        renderer.setBackgroundResource(android.R.color.darker_gray);
    }
    return renderer;
}

Of course, you can set the background color to whatever color you like to indicate that it's the "active" item.

like image 189
Blumer Avatar answered Nov 08 '22 05:11

Blumer