Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android List View set default position without animation

Tags:

java

android

I have a table list view in my app. and user can add more data in the list. I would like to show the default list view position at the newly added data. However, I use if I use smoothScrollToPosition, there is animation slowly scrolling down, which is not desirable. How do I set the default position without that animation?

like image 243
justicepenny Avatar asked Mar 31 '11 08:03

justicepenny


2 Answers

I think ListView.setSelection(int position) is what you need.

like image 169
ernazm Avatar answered Nov 04 '22 23:11

ernazm


In my app I had a similar need. I used getListView().setSelection() to define the position of the list, it works well without scroll.

If you consider having 2 activities, ActivityA which shows the list from a cursor and ActivityB which has a form to add a new item. On finish, ActivityB should return the item cursor id, then ActivityB can retrieve the position of the item with the id, and set the position, like this code :

/* check intent Id to scroll to the right item after update or delete */
if ( getIntent().hasExtra( ITEMID_INTENT_KEY ) )
{
    long id = getIntent().getLongExtra( ITEMID_INTENT_KEY, 0 );
    int position = getPositionFromId( id );
    getListView().setSelection( position > 0 ? position - 1 : 0 );
    getIntent().removeExtra( ITEMID_INTENT_KEY );
}

(...)

private int getPositionFromId( long id )
{
    mCursor.moveToFirst();
    do
    {
        Long cursorId = mCursor.getLong( mCursor.getColumnIndexOrThrow( yourIdColumn ) );
        if ( cursorId.longValue() == id )
        {
            return mCursor.getPosition();
        }
    }
    while ( mCursor.moveToNext() );
    return 0;
}
like image 32
tbruyelle Avatar answered Nov 05 '22 00:11

tbruyelle