你的位置:首页 > 操作系统

[操作系统]Android 常用数据适配器SimpleAdapter


在《Android 常用数据适配器ArrayAdapter》中介绍了ArrayAdapter数据适配器。但是存在一个缺陷,那就是条目的图标都固定相同,要显示每个条目的图标都不相同,那么使用SimpleAdapter

新建项目后,在layout文件夹下新建list_item.

<??><LinearLayout ="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:gravity="center_vertical"  android:orientation="horizontal" >  <ImageView    android:id="@+id/iv"    android:layout_width="wrap_content"    android:layout_height="wrap_content" />  <TextView    android:id="@+id/tv"    android:layout_width="wrap_content"    android:layout_height="wrap_content" /></LinearLayout>

activity_main.

<RelativeLayout ="http://schemas.android.com/apk/res/android"  ="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:paddingBottom="@dimen/activity_vertical_margin"  tools:context=".MainActivity" >  <ListView    android:id="@+id/lv"    android:layout_width="fill_parent"    android:layout_height="fill_parent" /></RelativeLayout>

从……\sdk\platforms\android-18\data\res\drawable-hdpi中随便拷贝几个图片,放到drawable-hdpi文件夹中

代码如下:

package com.wuyudong.simpleadapter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.ListView;import android.widget.SimpleAdapter;public class MainActivity extends Activity {  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    ListView lv = (ListView) findViewById(R.id.lv);    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();    Map<String, Object> map1 = new HashMap<String, Object>();    map1.put("nametext", "我是第1个功能");    map1.put("iconid", R.drawable.btn_radio_off_disabled_focused_holo_dark);    Map<String, Object> map2 = new HashMap<String, Object>();    map2.put("nametext", "我是第2个功能");    map2.put("iconid", R.drawable.btn_radio_off_disabled_focused_holo_light);    Map<String, Object> map3 = new HashMap<String, Object>();    map3.put("nametext", "我是第3个功能");    map3.put("iconid", R.drawable.btn_radio_off_focused_holo_dark);    Map<String, Object> map4 = new HashMap<String, Object>();    map4.put("nametext", "我是第4个功能");    map4.put("iconid", R.drawable.btn_radio_off_focused_holo_light);    Map<String, Object> map5 = new HashMap<String, Object>();    map5.put("nametext", "我是第5个功能");    map5.put("iconid", R.drawable.btn_radio_off_holo);    data.add(map1);    data.add(map2);    data.add(map3);    data.add(map4);    data.add(map5);    lv.setAdapter(new SimpleAdapter(this, data, R.layout.list_item,        new String[] { "nametext", "iconid" }, new int[]{R.id.tv, R.id.iv}));  }}

运行后的效果如下: