ListView非常常用,它可以实现信息列表化及对列表信息的选择,这是实现往ListView各种适配器添加数据。适配器种类主要有SimpleAdapter,ArrayAdapter<T>,还有一种就是自己自定义的适配器。这里通过一个ListView控件使用各种适配器添加数据。
首先定义一个主布局,在主布局里面添加一个TextView控件和一个ListView控件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="你选择了:"
/>
<ListView
android:layout_below="@+id/tv2"
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
接下来编写ListView控件中每个条目中的布局,也可以在代码中动态添加ListView的条目布局。条目简单的定义一个ImageView控件和一个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">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="@+id/tv"
android:layout_weight="1"
/>
</LinearLayout>
最后一步就是在activity中实现ListView控件数据的添加,我将实现三种适配器数据的添加。首先第一种实现SimpleAdapter适配器。
package co