【问题标题】:How to optimize Android ListView?如何优化Android ListView?
【发布时间】:2013-04-24 19:53:27
【问题描述】:

我已经自定义了我的 ListAdapter,并在 1 行中显示了 3 个不同的图像(项目)。 它完美地工作(根据它的功能)。 但是,无法平滑滚动 ListView。

我在 ImageViews 上使用 setBackgroundImage,我使用 HashMap 来缓存 resourceId;所以我不必使用

resId=getContext().getResources().getIdentifier(resName, "drawable",appContext.getPackageName());

一次又一次。

我想我错过了一些东西,因为 ListView 不能很好地滚动。另外,如果我在平板电脑上尝试,我的代码会自动在一行中填充 3 个以上的项目,平板电脑的列表视图几乎无法滚动。

我在这里做错了什么?

更新:

我在我的 Flags(国家标志)Activity 的 onCreate 方法中以编程方式创建 ListView:

root=(ViewGroup)this.findViewById(R.id.root);

    listView=new ListView(this);
    listView.setLayoutParams(new LayoutParams(
        LayoutParams.MATCH_PARENT,
        LayoutParams.MATCH_PARENT));

    /*
    ArrayList<Country> dataList=new ArrayList<Country>(){{
        add(new Country("jp"));
        add(new Country("de"));
        add(new Country("it"));
    }};*/

    CountryListAdapter countryListAdapter=new CountryListAdapter(this);


    countryListAdapter.setDataSource(allCountries);


    listView.setAdapter(regionListAdapter);
    listView.setBackgroundColor(0xFF000000);
    listView.setDividerHeight(0);

    root.addView(listView);

【问题讨论】:

  • “不太好”和“顺利”是什么意思?
  • 至少向我们展示您为 ListView 项创建视图的代码。
  • 使用 Traceview 准确确定您将时间花在哪里。此外,请StrictMode 就主应用程序线程上的明显问题向您大喊大叫。
  • 为了更好的平滑滚动使用ViewHolder和后台线程。您可以查看this 一个。

标签: android listview


【解决方案1】:

学习,学习和学习;-)

我的提示是使用ViewHolder模式,用于大量相同布局的项目(即使它是最简单的,例如单个TextView)

还有这个ViewHolder 实现示例/库

此外,如果您确实在 ListView 项目布局中使用图像,您可以使用一些库来异步下载图像,例如:

【讨论】:

    【解决方案2】:
    1. 使用静态 ViewHolder 模式

    2. 膨胀布局是一项昂贵的任务,因此尽可能避免膨胀布局
      替换

      LayoutInflater mInflater = LayoutInflater.from(context);
      convertView = mInflater.inflate(R.layout.listview_item, null);
      

      if (convertView == null) {
      
          LayoutInflater mInflater = LayoutInflater.from(context);
          convertView = mInflater.inflate(R.layout.listview_item, null);
      }
      
    3. 在单独的线程中执行图像加载任务,因此 getView 仅专注于视图绘图

    4. 在您的活动主题中添加&lt;item name="android:windowNoTitle"&gt;true&lt;/item&gt;

    5. 在 ListView 中添加属性 android:animationCache="false"

    6. 在 ListView 中添加属性 android:scrollingCache="false"

    【讨论】:

      【解决方案3】:

      您应该使用View Holder 模式,同时在没有连接调试器的情况下测试滚动是否缓慢。

      【讨论】:

        猜你喜欢
        • 2017-04-04
        • 1970-01-01
        • 1970-01-01
        • 2016-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多