为什么adapter.invalidate不会强制重新绘制新列表?

时间:2014-07-23 14:57:25

标签: java android android-listview

我有这段代码:

if (mOffersList == null || index == 0) {
    mOffersList = new ArrayList<Offer>();
}

try {
    mOffersList
        .addAll((Collection<? extends Offer>) gson
        .fromJson(result, collectionType));
} catch (Exception e) {
    // TODO: error in result: Nullable object must have
    // a value.
}

if (mOffersList == null || mOffersList.size() == 0) {
    errorMsg.setText("no offers found");
    hadError = true;
} else {
    if (mAdapter == null) {
        mAdapter = new ImageAdapter(
            OffersListActivity.this, mOffersList,
                listType);
        mListView.setAdapter(mAdapter);
    }
    mAdapter.notifyDataSetChanged();
    // mListView.invalidate();
}

代码贯穿始终 mOffersList = new ArrayList<Offer>();

然后添加新元素(仅3个项目),然后添加mAdapter.notifyDataSetChanged();

但在我的活动中显示旧列表(20个项目),而不是新列表。

怎么回事?

1 个答案:

答案 0 :(得分:-1)

如果要更新适配器,则不能只更新对象列表:还必须更新适配器。

为此,我总是使用这种方法:

void updateAdapter() {
    //Delete the content of the adapter
    adapter.clear();

    //Add new content to the adapter (datas is an arrayList of MyObject)
    for (MyObject obj : datas) {
        adapter.add(obj);
    }

    adapter.notifyDataSetChanged();
    listView.setAdapter(adapter);
}

希望它会有所帮助