Search code examples
androidlistactivityandroid-scroll

How to scroll to a child element in a ListActivity


I have a ListActivity class that populates a list using a CursorAdapter. What I need to do is have the view scroll down to a specific element within the list, based on the values of elements in the list.

The list is a list of items with 'due dates' and if the due date has already passed, I want the view to scroll past it. Therefore upon launch, the user will see the item with the nearest due date at the top (the view will be scrolled to this item). If they want to see past due dates, they can scroll up.

I hope I'm explaining this properly, I simply want to hide items in my ListActivity if their due date has already passed, based on the time the Activity is launched of course.


Solution

  • This works:

    ListView list = getListView();
    int count = list.getCount();
    
    long now = new GregorianCalendar().getTimeInMillis();
    int scrollTo = 0;
    
    for ( int i = 0; i < count; i++ ) {
        Cursor cursor = (Cursor)list.getItemAtPosition( i );
        long endtime = cursor.getLong( "endtime" );
        if ( endtime > now ) {
            //this is the one we want to scroll to
            scrollTo = i;
            break;
        }
    }
    temp.setSelection( scrollTo );