【问题标题】:How to maintain ListView position when using the new Loader APIs?使用新的 Loader API 时如何保持 ListView 的位置?
【发布时间】:2011-08-28 00:11:17
【问题描述】:

在 Honeycomb 中,Loader API 被引入作为通过在后台线程上执行繁重的工作来向应用程序提供数据的正确方法。在我的应用程序中,我正在努力用返回Cursors 的Loaders 替换我的所有Cursors。由于Cursor.requery() 现在已贬值,建议只调用restartLoader 并允许在后台线程上再次完成工作,然后在onLoadFinished 返回时changeCursor

除了 ListView 在我想重新查询数据时不保持其滚动位置之外,所有这些都非常有效,使用 Cursor.requery() 这曾经可以工作,因为它是具有更新数据的相同 Cursor 实例。

如何在不丢失滚动位置的情况下刷新我的加载器?

【问题讨论】:

  • 刷新前可以使用getScrollX()getScrollY()缓存,然后再手动设置。我不确定这是否会导致视觉闪烁或其他不愉快。 :-/

标签: android android-listview android-support-library android-cursor


【解决方案1】:

Loader 类本身不知道数据集何时更改,并且当前是特定于 CursorLoader 的实现。现在在我的应用程序中,我需要刷新的数据位于本地 SQLite 数据库(无 ContentProvider)中,因此我不得不修改 CursorLoader 以改用我的本地数据库,正如 Dianne Hackborne 在 developer group 中提到的那样。

不幸的是,仅仅从 loadInBackground 返回一个 Cursor 并不允许 ContentObserver 在数据更改时正确通知 Loader,这是因为 AbstractCursor 仅在 Cursor 上调用 requery() 时才调用 notifyChanged()

由于ContentObserver 永远不会通知Loader 数据已更改,因此我最终根据需要自己致电Loader.onContentChanged()。在这一点上,一切似乎都在工作,但如果出现任何重大问题,我会更新这个答案。

【讨论】:

    【解决方案2】:

    你必须不要在每个加载器加载时创建一个新的适配器;我的意思是..

    @Override
        public void onLoadFinished(Loader<List<NotificationItem>> loader, List<NotificationItem> notifications) {
            // We must do it in this way to not losing listview scroll position after a reload.
            if(mAdapter==null) {
                mAdapter = new HomeUserActivityListAdapter(getActivity(), notifications);
                mListView.setAdapter(mAdapter);
    
            }else{
                mAdapter.refill(notifications);
            }
        }
    

    然后在你的适配器中创建一个方法来重新填充物品

    public void refill(List<NotificationItem> notifications) {
        mNotificationsList.clear();
        mNotificationsList.addAll(notifications);
        notifyDataSetChanged();
    }
    

    仅此而已,它将准确地保持您的滚动位置:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 2012-03-04
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      相关资源
      最近更新 更多