Android 的SimpleAdapter几点认识
这个类是一个大家一看就明白的适用于数据绑定或者说数据渲染的一个类,只是这个类有些复杂,复杂之处在于其参数的设定,以及加载的形式上,官方文档上说是一个简单的Adapter,不过在我们基础入门而言已经算是复杂的了,他的继承结构层次是:
ava.lang.Object
↳Android.widget.BaseAdapter
↳Android.widget.SimpleAdapter
它的构造函数是:
public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
官方说明了其各个参数含义,我这里根据自己的理解解释下:
第一个context,很明显大家根据英文可以知道是上下文的意思,它官方的意思是:SimpleAdapter所要运行关联到的视图,这个是什么呢?就是你这个SimpleAdapter所在的Activity(一般而言),所以这个参数一般是this
第二个是一个泛型只要是一个List就行,这一般会想到是ArrayList,而他内部存储的则是Map或者继承自Map的对象,比如HashMap,这些语法都是Java的基本语法,不再详述了!这里呢是作为数据源,而且每一个ArraList中的一行就代表着呈现出来的一行,Map的键就是这一行的列名,值也是有列名的。
第三个资源文件,就是说要加载这个两列所需要的视图资源文件,你可以左边一个TextView右边一个TextView,目的在于呈现左右两列的值!
第四个参数是一个数组,主要是将Map对象中的名称映射到列名,一一对应
第五个是将第四个参数的值一一对象的显示(一一对应)在接下来的int形的id数组中,这个id数组就是LayOut的xml文件中命名id形成的唯一的int型标识符
这样也就达到了数据的列表呈现!
例子:
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@+id/listView1"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</LinearLayout>
在layout/目录下编写用于布局列表项内容的XML布局文件items.xml
Items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:paddingRight="10px"
android:paddingTop="20px"
android:paddingBottom="20px"
android:adjustViewBounds="true"
android:maxWidth="72px"
android:maxHeight="72px"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10px"
android:layout_gravity="center"
android:id="@+id/title"
/>
</LinearLayout>
MainActivity.java