更好的重现列表视图适配器或清除和重新填充? [英] Better to recreate listview adapter or to clear and repopulate?

查看:188
本文介绍了更好的重现列表视图适配器或清除和重新填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个的ListView CustomAdapter 键,让我们说我有这样的刷新()方法刷新,新的结果列表中,我应该:

If I have a ListView with a CustomAdapter and let's say I have this refresh() method that refreshes the list with new results, should I:


  1. 呼叫新CustomAdapter(...)初始化时,每次我打电话时间刷新(),我用 adapter.clear() adapter.add(...)

  1. Call new CustomAdapter(...) upon initialization, and every time I call refresh(), I use adapter.clear() and adapter.add(...)

呼叫新CustomAdapter(...)每次我打电话刷新时间()

基本上,我问,是它更好地重建一个适配器,每次我加载新的结果还是更以清除现有的适配器的结果和整个列表添加到它?

Basically, I'm asking, is it better to recreate an adapter everytime I load new results or is it better to clear the results in existing adapter and add the entire list to it?

推荐答案

这绝对是更好地称之为 notifyDataSetChanged()原适配器不是设置新的上之一。

It is definitely better to call notifyDataSetChanged() on the original adapter than setting a new one.

原因是性能:的ListView 使用视图回收,以避免当滚动创建新项目的意见。当您设置一个新的适配器,这些回收的意见都将被丢弃,这意味着它们必须从头开始重新创建下一个布局传递。看看在<一个href=\"https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/ListView.java\"相对=nofollow> ListView.setAdapter()的code

The reason is performance: ListView uses view recycling to avoid creating new item views as you scroll. When you set a new adapter, these recycled views are discarded, which means they must be recreated from scratch for the next layout pass. Take a look at the code of ListView.setAdapter():

@Override
public void setAdapter(ListAdapter adapter) {
    if (mAdapter != null && mDataSetObserver != null) {
        mAdapter.unregisterDataSetObserver(mDataSetObserver);
    }

    resetList();
    mRecycler.clear();

    ...

这是完全合乎逻辑的行为,因为的ListView 设新的适配器将使用的意见是由previous适配器返回的那些不兼容的(在任何情况下,它不能<青霉>假设的,他们将兼容)。所以他们扔掉。

This is completely logical behavior, since the ListView supposes that the views the new adapter will use are incompatible with the ones returned by the previous adapter (in any case, it cannot assume that they will be compatible). So they're thrown away.

因此​​,如果每次都设置一个新的适配器,你招致不必要的性能开销(重建所有当前视图)。

Therefore, if you set a new adapter each time, you're incurring an unnecessary performance cost (recreating all the current views).

另外,如果你写了一个的自定义的适配器,你不必叫添加()单独(与,说, ArrayAdapter )。你可以只用新的和呼叫 notifyDataSetChanged()之后。

Also, if you wrote a custom adapter, you don't necessarily have to call add() individually (as with, say, ArrayAdapter). You can just replace the internal data collection with the new one and call notifyDataSetChanged() afterwards.

这篇关于更好的重现列表视图适配器或清除和重新填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆