在面试的时候经常会被问到一个有关ListView的问题:一个ListView的高度最多可以显示5个item,但是却有20条数据要显示,问最多会有多少个convertView会被复用?或者如在ListView的Adapter中,在以Google推荐的方式进行view的复用时,convertView为null时要对convertView进行新建,那么新建的convertView最多会有多少个?或者convertView为null的情况下最多的个数是多少?
对这个问题的原理酝酿了好久,今天终于有时间对其进行验证。写了个测试用的Demo,用于分析两种情况下null的convertView的个数:单一种类item和多种类item。
首先对最简单、最常见的情况进行验证:单一种类item。
首先建了一个测试工程:LVItemCountTest。里面只有一个Activity---MainActivity。
其中的布局文件非常简单,activity_main.xml,详情如下:
1 <LinearLayout xmlns:andro 2 xmlns:tools="http://schemas.android.com/tools" 3 android: 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 tools:context="com.example.lvitemcounttest.MainActivity" 8 tools:ignore="MergeRootFrame" > 9 10 <TextView 11 android:layout_width="fill_parent" 12 android:layout_height="20dp" 13 android:text="ListView Item convertView test" /> 14 15 <ListView 16 android: 17 android:layout_width="fill_parent" 18 android:layout_height="300dp" > 19 </ListView> 20 21 </LinearLayout>