在上一篇文章中,我们是直接将一个String的ArrayList传给ArrayAdapter,然后ArrayAdapter会将其中的字符串一个一个地放到对应item上的TextView中,最终展示出来。
但是当时我们用的是android系统中提供的布局文件,我们可以用自己提供的布局文件吗?当然是可以的。
如下,我们在layout文件中定义一个arrayadapter.xml,在里面放上一个TextView(这个TextView可是一定要的,因为要用来展示字符串的),如下:
<?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="horizontal" >
<TextView android:id="@+id/textView1"
android:drawableLeft="@drawable/ic_launcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a layout to use when
* instantiating views.
* @param textViewResourceId The id of the TextView within the layout resource to be populated
* @param objects The objects to represent in the ListView.
*/
public ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects) {
init(context, resource, textViewResourceId, objects);
}其中resource还是布局文件,不过是我们自定义的layout文件了,而textViewResourceId就是我们定义的textView了,下面是Activity中的代码:
ListView listView = (ListView)findViewById(R.id.listView1); // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.arrayadater, R.id.textView1, list); listView.setAdapter(adapter);只是利用一个新的构造函数重新创建了一个ArrayAdapter对象,下面是效果图:
在上面,我们只是定义了一个TextView,那么,我们是不是可以定义多一个其它的component呢,比如再定义一个Checkbox呢,我们来试试吧。
<?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="horizontal" >
<CheckBox android:id="@+id/checkbox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/textView1"
android:drawableLeft="@drawable/ic_launcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
接下来看看效果图:
我们可以看到Checkbox出来了,那我们现在随便选中几个吧,然后继续往下拉,我们可以看到,下面的item,还是被选中了,为什么呢?这正好说明了,这些view的确是在一直被重新利用的。
Android中关于ListView的使用(再上)ArrayAdapter
原文:http://blog.csdn.net/linmiansheng/article/details/19243149