应用场景
Item包含了比较耗内存的布局,比如需要展示大图的ImageView,VideoView,WebView等。这时候滑动ListView往往会出现滑动不流畅甚至OOM的情况。
解决思路
我们拿ImageView来说明问题。假设我们要在Item中展示的ImageView非常占用内存,如果我们要在一个屏幕上把当前显示的Item中的ImageView全部加载出来,应用会卡死。这时我们可以在需要展示ImageView对象的地方展示它,在不要的地方清除它。具体可以这么办:
- 在Item的布局文件中需要展示ImageView的地方放一个container比如说LinearLayout
- 在Adapter的构造函数中生成一个全局ImageView对象,这个对象就是我们要展示的ImageView
- 在Adapter的getView()方法中给Item中某个控件设置一个OnClickListener(),在OnClickListener中将ImageView添加到container中,并给这个imageView添加需要展示的图片。
- 在return convertView之前,调用container的reMoveAllViews()方法,移除当前container中的ImageView。
关键代码
Item布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="200dp">
<!--ImageView的容器-->
<LinearLayout
android:id="@+id/linear_container&