Android中关于Adapter的使用(再上)ArrayAdapter

来源:互联网 发布:三国大时代3无需网络破 编辑:程序博客网 时间:2024/04/26 14:28

在上一篇文章中,我们是直接将一个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>

在TextView的旁边放了一个小图标,不过这样的话,在创建Adapter的时候,就必须用另外一个构造函数了,因为要告诉ArrayAdapter,要用哪个TextView去显示字符串啊。

    /**     * 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, 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的确是在一直被重新利用的。

大家有兴趣,可以接下去看关于SimpleAdapter的使用:
Android中关于Adapter的使用(中)SimpleAdapter
或者再看一下上一篇文章:
Android中关于Adapter的使用(上)ArrayAdapter
0 0
原创粉丝点击