A frequently discussed topic when developing Android applications using ListActivity is how to specify the displayed item of the embedded ListView.
Once we call the
setSelection(int position) when UI is visible, everything works fine, the ListView will scroll to the item smoothly. The problem is that if we specify a position before the ListActivity/ListViews are created, calling to this function seems not working, the ListView always emerged as if no setSelection was called.
An usual option to fix this problem is using delayed execution of
setSelection() as below:
protected void onCreate(Bundle savedInstanceState)
listView = getListView();
position = ...
BaseAdapter adapter = ...;
public void run()
Although the post (Runnable) did scroll the ListView as expected, it happened only after the ListView was first showed the top-most item.
Using the code
To enhance the presentation of the ListView/ListActivity, the trick is extremely simple by invalidate the ListView immediately after
That is all, the adapter will trigger the ListView present the expected item before it is shown.
Points of Interest
Another interesting issue I realized was that when start a new ListActivity with a bundle, be sure to pack
the values within a bundle.
Intent intent = new Intent(CallerActivity.this, MyListActivity.class);
Bundle bundle = new Bundle();
Otherwise, the called
ListActivity will only get a null