您的位置:首页 > 移动开发 > Android开发

Android笔记(二十一) Android中的Adapter

2015-09-04 17:32 363 查看
Android中有一些View是包含多个元素的,例如ListView,GridView等,为了给View的每一个元素都设置数据,就需要Adapter了。

常用的Adapter包括ArrayAdapter和SimpleAdapter。

ArrayAdapter

ArrayAdapter比较简单,它只能用于显示文字。看代码:

MainActivity.java

<?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:weightSum="1">

<ImageView
android:id="@+id/iv_fruit_show"
android:layout_width="80dp"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:src="@drawable/pic0"/>

<TextView
android:id="@+id/tv_fruit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1111"
android:textSize="50dp" />

</LinearLayout>


View Code

  

查看API,发现SimpleAdapter可以将静态数据映射到xml文件定义好的视图中去,你可以指定数据支持的列表如ArrayList组成的Map,在ArrayList中的每个条目对应List中的一行,Maps包含每行数据,你可以指定一个定义了被用于显示行的视图XML文件,通过关键字映射到指定的视图。绑定数据到视图分为两个阶段,首先,如果一个SimpleAdapter.ViewBinder是有效的,setViewValue(android.View.view,Object,String)将被调用。如果返回值是真,绑定成功,如果返回值为假,下面的视图将按照以下顺去去处理:

l 一个实现了Checkable的视图(例如CheckBox),期望绑定值是一个布尔类型。

l TextView期望绑定值是一个字符串类型,通过调用setViewText(TextView, String)绑定。

l ImageView期望绑定值是一个资源id或者一个字符串,通过调用setViewImage(ImageView, int) 或 setViewImage(ImageView, String)。

  如果没有一个合适的绑定发生将会抛出IllegalStateException

SimpleAdapter的构造函数

public SimpleAdapter(Context context, List<?extends Map<String,?>> data, int resource, String[] from, int[] to)

参数:

context:关联SimpleAdapter运行着的视图的上下文

data:一个Map列表,在列表中的每个条目对应列表中的一行,应该包含所有在from指定的条目

resource:一个定义列表项目视图布局的资源唯一表示。布局文件将至少应包含哪些定义在to中定义了的名称

from:一个将被添加到Map上关联每一个项目的列名称的列表

to:应该在参数from显示列的视图,这些应该全是TextView。在列表中最初的N视图是从参数from中最初的N列获取的值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: