android ListView:scrollTo不起作用

Ale*_*xis 6 android cursor android-listview simplecursoradapter

我有一个视图,其中包含一个绑定到游标适配器的ListView.当光标内容发生变化时,我想将ListView保持在顶部,然后在我的自定义光标适配器中添加:

@Override
protected void onContentChanged() {
    // ...
    myListView.scrollTo(0, 0);
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.然后我读到某个地方将这个动作排队如下:

myListView.post(new Runnable() {
    public void run() {
        myListView.scrollTo(0, 0);
    }
});
Run Code Online (Sandbox Code Playgroud)

但这也不起作用.

当内容发生变化时,如何将ListView保持在顶部?

编辑:

只是为了尝试,我添加了一个按钮,并在其onClickListener中调用scrollTo(),它不起作用!我错过了什么?

Eld*_*abu 29

而不是scrollTo,尝试使用setSelection(0)到达列表视图的顶部位置.

  • 有用!!但为什么??为什么scrollTo()不起作用? (4认同)

Dil*_*eet 7

我制作的功能对于listview滚动的其他人很有用,它们适用于我的每个Android版本,模拟器和设备,这里itemheight是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;
}
Run Code Online (Sandbox Code Playgroud)

  • @Diljeet我改进了scrollToY的代码,它不假设每个项目的高度相同.而不是从高处计算项目位置.只需将该位置插入setPositionFromTop https://gist.github.com/Kisty/e2c3cd956a01a19661e8 (2认同)

wea*_*ire 6

ListView scrollTo适用于ListView它自己作为一个View

setSelection(0) 这个技巧是因为它适用于listview的适配器