ListView是Android开发中比较常用的一个组件,它以列表的形式展示信息,并能根据信息的长度自适应显示。比如说我们手机里的通讯录就用到了ListView显示联系人信息。在大量的场合下,我们都需要使用这个控件。虽然在Android 5.0时代,RecyclerView在很多地方都在逐渐取代ListView,但ListView的使用范围依然非常的广泛。我们也不能跳过ListView直接去学习RecyclerView,对ListView的透彻理解是十分有必要的。
首先来看ListView在View树中所处的位置:
ListView的官方解释:
A view that shows items in a vertically scrolling list.
The items come from the {@link ListAdapter} associated with this view.
即:一种在垂直滚动列表中显示项目的视图。
显示的项目(数据)通过ListAdapter适配器来与视图关联。
数据适配器是连接数据源和视图界面的桥梁,它用来把复杂的数据(数组、链表、数据库、集合等)填充在指定视图界面上。数据适配器的实现过程为:1.新建适配器–>2.添加数据源到适配器–>3.视图加载适配器。
那么ListAdapter是什么适配器呢?Adapter是所有适配器的祖先接口,下图为ListAdapter在所有适配器继承树中的位置:
自定义数据适配器的时候用到了BaseAdapter类,那么ListAdapter和BaseAdapter是什么关系呢?只看名字好像BaseAdapter是ListAdapter的长辈,但实际上ListAdapter是所有可以用于ListView的适配器的祖先,且仅仅为一个接口。下面为ListAdapter的继承树:
这样,显示的项目(数据)通过ListAdapter适配器来与视图关联这句话的含义便很易理解了,不管是ArrayAdapter、SimpleAdapter、SimpleCursorAdapter或者自定义BaseAdapter,只要这些适配器实现了ListAdapter接口,就可以统称为ListAdapter适配器,继而用于ListView的数据适配,下面为展开的继承树:
这下我们就不用去询问别人ListView有哪几种适配器了,我们已经自己推导出上图除红锁标记的私有类外的其他适配器都可以给ListView用。下面来看比较常用的四种适配器:ArrayAdapter、SimpleAdapter、SimpleCursorAdapter以及自定义BaseAdapter。
ArrayAdapter(数组适配器)
用于绑定格式单一的数据,数据源可以是集合或数组。
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<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">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
MainActivity.java 如下:
package com.example.listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
imp