Android:To set an item as selected when the ListView opens?
I post my solution, because google still doesn't know the answer.
getListView().setItemChecked(selectedGroupIndex, true);
In short, ListView::setSelection(int position) is what you need. However, depending on whether the device is in touch mode or not, it may or may not have visual effect (background highlighting). For more details, refer to Android ListView Selection Problem
If you use an Adapter
for your ListView
add this code to your adapter:
public class MyAdapter extends ArrayAdapter<MyClass> { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflator = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflator.inflate(R.layout.my_adapter, null); } else { rowView = (View) convertView; } //... // set selected item LinearLayout ActiveItem = (LinearLayout) rowView; if (position == selectedItem){ ActiveItem.setBackgroundResource(R.drawable.background_dark_blue); // for focus on it int top = (ActiveItem == null) ? 0 : ActiveItem.getTop(); ((ListView) parent).setSelectionFromTop(position, top); } else{ ActiveItem.setBackgroundResource(R.drawable.border02); } } private int selectedItem; public void setSelectedItem(int position) { selectedItem = position; } }
In your Activity
:
myAdapter.setSelectedItem(1);