Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android ListView : scrollTo doesn't work

I have a view that contains a ListView which is bound to a cursor adapter. When The cursor content change I want to keep the ListView at the top then in my custom cursor adapter I added :

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

but this doesn't work. Then I read somewhere to queue this action like this :

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

but this doesn't work either.

How can I keep the ListView at the top when its content changes?

EDIT:

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

like image 780
Alexis Avatar asked Sep 19 '12 09:09

Alexis


3 Answers

Instead of scrollTo, try setSelection(0) to get to the top position of list view.

like image 102
Eldhose M Babu Avatar answered Nov 02 '22 09:11

Eldhose M Babu


i made functions that could be useful for others for listview scrolling, they work for me in every android version, emulator and device, here itemheight is the fixed height of view in the listview.

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;
}
like image 35
Diljeet Avatar answered Nov 02 '22 08:11

Diljeet


ListView's scrollTo applies to the ListView it self as a View

setSelection(0) does the trick because it applies to the listview's adapter

like image 34
weakwire Avatar answered Nov 02 '22 09:11

weakwire