Android ListView滚动到顶部

aak*_*ash 80 android listview

我有ListView自定义行.单击任何这些行时,将重新生成ListView的数据.当发生这种情况时,我希望列表回滚到顶部.

I initially tried using setSelection(0) in each row's OnClickListener to achieve this but was unsuccessful (I believe because the ListView loses its scroll position when its data is invalidated - so my call to setSelection is undone. I still don't understand how the ListView decides where to scroll to after invalidation, though).

The only working solution I know of was given by Romain Guy here: http://groups.google.com/group/android-developers/browse_thread/thread/127ca57414035301

It involves (View.post)ing the call to _listView.setSelection(0). I found this to perform quite poorly. The newly generated list shows up with its scroll location unchanged and there is a considerable delay before it scrolls back to the top.

Is there any better way to achieve this functionality?

Any help would be much appreciated.

Thanks!

小智 129

打电话listView.setSelectionAfterHeaderView();滚动到顶部

  • 这正是我所说的. (64认同)

N20*_*753 101

我尝试了很多,但这个对我有用

list.smoothScrollToPosition(0);
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:需要API 8+ (3认同)
  • 这太棒了.我想知道你是否可以改变滚动速度. (3认同)

rad*_*hoo 39

我只是用 listview.setSelection(0);

对我来说很好.


Dmi*_*nov 5

如果在ListView适配器数据更改后需要立即滚动,请注意它可能尚未填充.在这种情况下,你应该通过post()setSelection()或者setSelectionAfterHeaderView()通过Handler这样的方式稍后在队列中调用它.

listView.Handler.post(new Runnable() {
            @Override
            public void run() {
                listView.setSelectionAfterHeaderView();    
            }
        });
Run Code Online (Sandbox Code Playgroud)

这对我有用.


Com*_*are 4

就我个人而言,我建议您寻找不同的 UI 模式。用户可能会发现您当前的“点击,列表就地更改”的方法很直观,但我对此表示怀疑。

您可以尝试子类化ListView和重写layoutChildren()以链接到超类,然后setSelection(0)在需要的情况下调用。如果“相当大的延迟”只是由于post()通话造成的,那么这应该可以解决问题。

  • 感谢您的建议,我很快就会尝试一下。该列表会就地更改,因为面包屑显示在屏幕上的其他位置 - 典型的 Android UI 设计不太适合我的特定 UI 目标和目标用户。另外,感谢您的所有帮助 - 我已经阅读了您的一些 stackoverflow 答案和 CommonsWare 文献,它们对我开始使用这个平台有很大帮助! (4认同)