在CursorAdapter中更改游标未正确更新列表项视图

时间:2013-06-08 21:55:06

标签: android android-listview cursor android-cursoradapter notifydatasetchanged

这个问题与StackOverflow上的许多其他问题非常相似,但我认为由于方法上与其他问题相比存在差异,因此它有自己的优势。

我有一个扩展CursorAdapter的自定义适配器。我正在更新数据并在相应的URI上调用notifyChange以刷新光标。在调试中,我可以看到它正常工作。

不幸的是,我的列表视图没有被重新创建。我需要重新创建它们的原因是因为我在适配器上实现了newView

public View newView(final Context context, final Ingredient ingredient, final ViewGroup parent) {
    final int layout = ingredient.isOwned() ? LAYOUT_OWNED : LAYOUT_UNOWNED;
    final View view = LayoutInflater.from(context).inflate(layout, null);

    // ... ViewHolder magic

    return view;
}

问题是调用notifyChange正在更新列表数据,但是它没有通过newView重新创建我需要的视图。

以下是我尝试的其他一些同样不起作用的事情:

  • 在数据更新后调用adapter.notifyDataSetChanged()
  • 在数据更新后调用contentResolver.notifyChange(...)后跟adapter.notifyDataSetChanged()
  • 名为adapter.changeCursor(newCursor),后跟adapter.notifyDataSetChanged()
  • 在已更改的特定列表项上调用view.invalidate()

关于如何处理此事的任何其他建议?

编辑:我可能只是采取了错误的做法。我误解了适配器中视图的回收,我发现在回收时使用了错误的视图类型。因此,我可能需要使用另一种方法来设计我的观点。我之所以采用这种方法,是因为我希望使用样式,除了将视图扩展为explained in this StackOverflow question之外,不能以编程方式设置。我愿意采用能够在正确回收列表项视图的同时利用该答案的方法。

1 个答案:

答案 0 :(得分:1)

我最终根据this StackOverflow answer找出了问题。我需要覆盖适配器上的getItemTypeCountgetItemViewType

@Override
public int getItemViewType(int position) {
    return getItem(position).isOwned() ? 1 : 0;
}

@Override
public int getViewTypeCount() {
    return 2;
}