更新SimpleCursorAdapter,同时在ListView中保持滚动位置

时间:2012-02-13 05:07:55

标签: android listview simplecursoradapter scroll-position

我的问题:每当我通过其(自定义的)SimpleCursorAdapter更新其内容时,我的ListView会将其滚动位置重置为顶部。我希望ListView在更新时保持其滚动位置。

我开始时每次都使用ListView.setAdapter()创建一个新的适配器实例,但根据this discussion我应该更新适配器而不是重置它。我无法找到一种方法来为SimpleCursorAdapter正常工作。

以下是我尝试过的一些事情,省略了方法论点:
- SimpleCursorAdapter.changeCursorAndColumns()使用新光标成功更新适配器,但仍会重置滚动位置 - SimpleCursorAdapter.changeCursor()以同样的方式行事 - SimpleCursorAdapter.swapCursor()直到api 11才可用,我正在为api 8开发。
- SimpleCursorAdapter.notifyDataSetChanged()不更新ListView。 (也许我还缺少另一个步骤。)
- ListView.invalidate()不会更新ListView - SimpleCursorAdapter.requery()将ListView设为空白,不推荐使用 - 我熟悉ListView.setSelection()解决方案,但我不希望我的ListView在更新时完全移动。这会将其捕捉到列表中的某个位置。

这似乎应该是一个普通而简单的问题。有人处理过吗?

2 个答案:

答案 0 :(得分:5)

我遇到了类似的问题:只要光标内容发生变化,我的CursorAdapter就会重置滚动位置。

我没有意识到每次数据更改时我确实设置了一个新的列表适配器。我认为光标本身会通知适配器有关其内容的更改但在我的情况下是ContentProvider在我的ListFragment中触发LoaderManager.LoaderCallbacks.onLoadFinished()。在该回调中,我现在使用CursorAdapter.changeCursor()而不是创建一个新的适配器,一切正常。

我希望这有助于解决您的问题。

答案 1 :(得分:0)

在下面的代码中使用的Async Task的后执行中是否有相同的效果

 Cursor cursor = mDataHelper.getWritableDatabase().query(
                        DataContract.Incares.TABLE_NAME,  // Table to Query
                        null, // all columns
                        null, // Columns for the "where" clause
                        null, // Values for the "where" clause
                        null, // columns to group by
                        null, // columns to filter by row groups
                        DataContract.Incares.UUID +" DESC" // sort order
                );
CursorAdapter.swapCursor(cursor);
CursorAdapter.notifyDataSetChanged();

使用CursorAdapter作为全局变量

相关问题