ListView
调用ListView的setAdapter()方法,可以设置数据源。调用ListView的setOnItemClickListener()方法,可以注册点击事件。
ArrayAdapter
如果列表项只有一行字符串数据,可以使用ArrayAdapter。
ArrayAdapter的构造函数有三个参数:Context、ResourceID和字符串数组。
public ArrayAdapter(Context context, int textViewResourceId, T[] objects)
ResourceID缺省可以使用android.R.layout.simple_list_item_1,其实就是TextView。sdk/data/res/layout/simple_list_item_1.xml内容如下:
<TextView android:id="@android:id/text1
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
SimpleAdapter
如果列表项有两行字符串数据,可以使用SimpleAdapter。
SimpleAdapter的构造函数有5个参数:Context、List、ResourceID、From字符串数组、To整数数组。
public SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
List常见为:ArrayList<Map<String,Object>>
ResourceID缺省可以使用android.R.layout.simple_list_item2,是一个TwoLineListItem。sdk/data/res/layout/simple_list_item_2.xml内容如下:
<TwoLineListItem android:layout_width="match_parent" android:layout_height="wrap_content"
<TextView android:id="@android:id/text1" />
<TextView android:id="@adnroid:id/text2" />
</TowLineListItem>
From字符串数组:从List里的Map中根据From[i]作为key取值,也就是ArrayList[i].get[From[i]],可以是一个对象,不一定是字符串
To整数数组:资源XML里面的ID,从上面From中获取的数据,就放入到对于ID的控件中。
ListView工作原理
ListView开始绘制时,首先调用Adapter的getCount()得到总行数,然后调用getview()方法得到每一行具体的View。
public interface Adapter {
/**
* 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. When the View is inflated, the
* parent View (GridView, ListView...) will apply default layout parameters unless you use
* {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
* 得到一个View来显示数据集中特定位置的数据。可以手工创建一个View,也可以从XML文件生成一个View。
*
* @param position The position of the item within the adapter's data set of the item whose view
* we want.
* 在数据集中的位置
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* 可以重用的旧View。如果不能用这个View显示数据,也可以创建一个新的View。
* @param parent The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position.
*/
View getView(int position, View convertView, ViewGroup parent);
}