Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile

ListActivity setSelection within onCreate()

5.00/5 (1 vote)
23 Dec 2012CPOL 20.3K  
Specify the displayed position before launching a ListActivity

Introduction

A frequently discussed topic when developing Android applications using ListActivity is how to specify the displayed item of the embedded ListView.

Background

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:

Java
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    listView = getListView();
    
    //get desired item position of the listView
    position = ...
    
    // other operations   
    BaseAdapter adapter = ...; // get the adapter and
    listView.setAdapter(adapter);
    
    listView.post(new Runnable()
    {
        public void run()
        {
            listView.setSelection(position);
        }
    });
} 

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():  

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

//            } 
//        });
listView.setSelection(position);
adapter.notifyDataSetChanged(); 

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.

Java
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
intent.putExtras(bundle);
this.startActivity(intent);

Otherwise, the called ListActivity will only get a null savedInstanceState

History 

...

License

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