Android:PullToRefresh如何滚动到最顶部

阅读时间 约 1 分钟

一般如果用ListView,让它滚动到顶部,是这样写的:

if (!listView.isStackFromBottom()) {
    listView.setStackFromBottom(true);
}
listView.setStackFromBottom(false);

但是,使用PullToRefreshListView以后,发现该对象竟然没有setStackFromBottom()方法!

探究

翻翻它的源码,发现是这样的:

public class PullToRefreshListView extends PullToRefreshAdapterViewBase<ListView>{...}

它并不是继承于ListView,所以也无法将这个对象castListView

但是,实际上PullToRefreshListView的主体确实是一个ListView,那么如何使用属于ListView的方法呢?

原因

Google了半天,终于在stackoverflow上找到了答案:Retaining scroll position on Pull To Refresh

PullToRefresh为了实现各种不同的View的下拉刷新,并不是简单的继承自ListView,而是采用了泛型。

实际上可以理解为在ListView(或者其他想要实现下拉刷新的View)外面包了一层ParentView

想要得到里面的ListView,有这样一个方法:

listView.getRefreshableView();

解决

因此,想要让它回到顶部,代码如下:

ListView mlist = listView.getRefreshableView();
if (!(mlist).isStackFromBottom()) {
    mlist.setStackFromBottom(true);
}
mlist.setStackFromBottom(false);

解决问题!