Listview 通过adapter适配显示view
public View getView(int position, View convertView , ViewGroup parent){...}
这个方法就是用来获得指定位置要显示的View。官网解释如下:
Get a View that displays the data at the specified position in the data set. You can either create a View manually or inflate it from an XML layout file.
当要显示一个View就调用一次这个方法。这个方法是ListView性能好坏的关键。方法中有个convertView,这个是Android在为我们而做的缓存机制。
ListView中每个item都是通过getView返回并显示的,假如item有很多个,那么重复创建这么多对象来显示显然是不合理。因此,Android提供了Recycler,将没有正在显示的item放进RecycleBin,然后在显示新视图时从RecycleBin中复用这个View。
下面通过log来分析该种机制
public View getView(int position, View convertView, ViewGroup parent) {
CustomImageView im;
if (convertView == null) {
convertView = (View) mInflater.inflate(R.layout.list_image_item, parent, false);
im = (CustomImageView) convertView.findViewById(R.id.custom_image_item);
convertView.setTag(im);
Log.d("ImageAdapter", im.toString() + " position = " + position);
} else {
im = (CustomImageView) convertView.getTag();
Log.d("ImageAdapter", "getTag position = " + position + " " + im);
}
im.setImageResource(mUrl[position]);
return convertView;
}
custom_image_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.testandroid.widget.CustomImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/custom_image_item"/>
</LinearLayout>
最终Listview在屏幕可见范围只显示了2张图片
//初始化View屏幕显示的2张图片,getview执行三遍但最终将position = 0设置到423702f8对象
D/ImageAdapter(19318): com.example.testandroid.widget.CustomImageView{423702f8} position = 0
D/ImageAdapter(19318): getTag position = 1 com.example.testandroid.widget.CustomImageView{423702f8}
D/ImageAdapter(19318): getTag position = 0 com.example.testandroid.widget.CustomImageView{423702f8}
//初始化另一个view,直接将position = 1设置到42374e98对象
D/ImageAdapter(19318): com.example.testandroid.widget.CustomImageView{42374e98} position = 1
//多初始一个view引用为42376cc0,不管设置哪个资源,对用户都不可见
D/ImageAdapter(19318): com.example.testandroid.widget.CustomImageView{42376cc0} position = 0
D/ImageAdapter(19318): getTag position = 1 com.example.testandroid.widget.CustomImageView{42376cc0}
D/ImageAdapter(19318): getTag position = 0 com.example.testandroid.widget.CustomImageView{42376cc0}
D/ImageAdapter(19318): getTag position = 1 com.example.testandroid.widget.CustomImageView{42376cc0}
//滑动屏幕
D/ImageAdapter(19318): getTag position = 2 com.example.testandroid.widget.CustomImageView{42376cc0}
D/ImageAdapter(19318): getTag position = 3 com.example.testandroid.widget.CustomImageView{423702f8}
最终看到adapter只初始化了3个view,并将3个View放入Recycler,当用户滑动屏幕时由Recycler提供重用View,
因此在进行长时间任务更新时,需考虑数据更新错位现象