android ListView : scrollTo doesn't work

浪子不回头ぞ 提交于 2019-12-21 13:11:34

问题


I have a view that contains a ListView which is binded 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 ?


回答1:


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




回答2:


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;
}



回答3:


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



来源:https://stackoverflow.com/questions/12491855/android-listview-scrollto-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!