Click here to Skip to main content
13,556,249 members
Click here to Skip to main content
Add your own
alternative version


3 bookmarked
Posted 23 Dec 2012
Licenced CPOL

ListActivity setSelection within onCreate()

, 23 Dec 2012
Rate this:
Please Sign up or sign in to vote.
Specify the displayed position before launching a ListActivity


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();
    //get desired item position of the listView
    position = ...
    // other operations   
    BaseAdapter adapter = ...; // get the adapter and
    listView.setAdapter(adapter); Runnable()
        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 setSelection():  

// Runnable()
//        {
//            public void run()
//            {
//                listView.setSelection(position);

//            } 
//        });

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();
bundle.putString(KEY1, valueString);
bundle.putInt(KEY2, value2);

// put it as Extras into the intent

Otherwise, the called ListActivity will only get a null savedInstanceState




This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
Australia Australia
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03-2016 | 2.8.180515.1 | Last Updated 23 Dec 2012
Article Copyright 2012 by JIANGWilliam
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid