ListView用起来还是比较简单的,也是Android应用程序中最重要的一个组件,但其他ListView可以随你所愿,能够完成很多想要的精美列表,而这正是我们接下来要学习的内容。
一、自定义ArrayAdapter
从上期自定义列表项示例知道,每个列表项的图标都一样,如果需要每个列表项的图标根据内容动态表示,Android系统的ArrayAdapter就无能为力了,就只能使用自定义ArrayAdapter来实现啦。
做法就是创建一个ArrayAdapter的子类,重写其getView()方法,再构建不同的列表项。其中getView()方法返回的是一个View,也就是与Adapter数据对应的相应位置的行。
在学习自定义ArrayAdapter前,一起先来学习一下LayoutInflater类。在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件并实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。
LayoutInflater 是一个抽象类,获得 LayoutInflater 实例有以下三种方式。
// 通过Activity获取
LayoutInflaterinflater=getLayoutInflater();
// 通过静态方法获取
LayoutInflaterinflater=LayoutInflater.from(context);
// 通过系统服务获取
LayoutInflaterinflater= (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
其实这三种方式最终本质是都是调用的Context.getSystemService(),关于该方法的使用会在后续内容进行学习。
获得LayoutInflater 实例后,就可以调用inflater.inflater()方法来查找并实例化布局文件了,常用于获得ListView的每个Item布局。
二、示例
接下来用一个示例来学习如何自定义ArrayAdapter,需要重写getView()方法,在不同对的行中根据内容显示不同的图标。要显示的图标根据显示的字符串首字母来判断,如果以字母“a”或者“A”开头,就显示一张字母A的图标。
继续使用WidgetSample工程的listviewsample模块,在app/main/res/layout/目录下创建custom_arrayadapter_layout.xml文件,在其中填充如下代码片段:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
然后在res/layout/目录下新建一个custom_arrayadapter_item.xml的列表项布局文件,其代码如下:
<?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"
android:gravity="center_vertical">