Adapter常用来管理数据,是连接后端数据和前端显示的适配器接口,是数据和UI(view)之间一个重要的纽带。再常见的view(listview、gridview)等地方都需要用到adapter,下面我们来讲讲SimpleAdapter:
•SimpleAdapter类:一个使静态数据和在xml中定义的Views对应起来的简单adapter。
•构造方法:
SimpleAdapter adapter = new SimpleAdapter(context, List<?extends Map<String,?>> data, resource, from, to);
context:上下文,指这个适配器所运行的视图,一般是指在那个activity(界面)
data:一个泛型的List,适配器的数据源(一般使用ArrayList封装Map、HashMap对象)
resource:适配器xml视图的引用路径
from:参数是一个数组对象,主要是将Map的键映射到列名,一一对应
to:将“from”的值一一对应显示,是一个R文件的数组,一般是你所要加载数据的控件的ID数组.
list.setAdapter(adapter);
代码示例:
java代码:
package com.sumzom.arrayadp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.com.sumzom.lv.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ArrayAdpActivity extends Activity{
private ListView ary_list = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.arrayadp);
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("name","xoap");
list.add(map);
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("name","fnsjf");
list.add(map1);
SimpleAdapter adapter = new SimpleAdapter(
getApplicationContext(), list, R.layout.lv_item,
new String[]{"name"}, new int[]{R.id.tv} );
ary_list = (ListView) findViewById(R.id.ary_list);
ary_list.setAdapter(adapter);
}
}
xml代码:
activity绑定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="vertical" >
<ListView
android:id="@+id/ary_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
list 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="vertical" >
<LinearLayout
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我的第一个自定义适配器"
android:textColor="#ff00ff"/>
</LinearLayout>
</LinearLayout>
运行结果: