Android ListView: scrollTo not working

I have a view that contains a ListView bound to a cursor adapter. When the contents of the cursor change, I want the ListView to be on top, and then in my custom cursor adapter I added:

@Override
protected void onContentChanged() {
    // ...
    myListView.scrollTo(0, 0);
}

but it does not work. Then I read somewhere to queue this action as follows:

myListView.post(new Runnable() {
    public void run() {
        myListView.scrollTo(0, 0);
    }
});

but this also does not work.

How to save a ListView at the top of the page when changing its contents?

EDIT:

Just for a try, I added a button and called scrollTo () in my onClickListener, and that didn't work! What am I missing?

+5
source share
3 answers

scrollTo setSelection (0), .

+28

ListView scrollTo ListView View

setSelection(0) , listview

+5

i created functions that others can use to scroll through the list, they work for me in every version, emulator and device for Android, here itemheight is a fixed height of the view in the list.

int itemheight=60;
public void scrollToY(int position)
{
    int item=(int)Math.floor(position/itemheight);
    int scroll=(int) ((item*itemheight)-position);
    this.setSelectionFromTop(item, scroll);// Important
}
public void scrollByY(int position)
{
    position+=getListScrollY();
    int item=(int)Math.floor(position/itemheight);
    int scroll=(int) ((item*itemheight)-position);
    this.setSelectionFromTop(item, scroll);// Important
}
public int getListScrollY()
{
    try{
    //int tempscroll=this.getFirstVisiblePosition()*itemheight;// Important
    View v=this.getChildAt(0);
    int tempscroll=(this.getFirstVisiblePosition()*itemheight)-v.getTop();// Important
    return tempscroll;
    }catch(Exception e){}
    return 0;
}
+5
source

All Articles