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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With