使用SimpleAdapter创建ListView

来源:互联网 发布:node throw err 编辑:程序博客网 时间:2024/05/01 10:28
使用SimpleAdapter创建ListView
通过ArrayAdapter实现的Adapter虽然简单、易用,但功能有限,它只能通过每个列表项是TextView,如果需要实现更复杂的列表项,则可以使用SimpleAdapter。
SimpleAdapter并非如名字简单,它的功能非常强大,可实现ListView的大部分应用。
使用如下:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">        <ImageView         android:id="@+id/Img"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>        <TextView         android:id="@+id/name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toRightOf="@+id/Img"        android:gravity="center_vertical"        android:layout_marginLeft="20sp"/>        <TextView         android:id="@+id/country"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toRightOf="@+id/name"        android:layout_marginLeft="20sp"/></RelativeLayout>
package com.example.listview03_simpleadapter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.app.Activity;import android.os.Bundle;import android.widget.ListView;import android.widget.SimpleAdapter;public class MainActivity extends Activity {private String[] names = { "姚明", "Kobe", "贝克汉姆", "加索尔" };private String[] country = { "中国", "美国", "英国", "西班牙" };private int[] imgId = { R.drawable.j1a2, R.drawable.j1a4, R.drawable.j1a5,R.drawable.j1a6 };@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 创建一个List集合,集合元素师MapList<Map<String, Object>> listItem = new ArrayList<Map<String, Object>>();for (int i = 0; i < names.length; i++) {Map<String, Object> map = new HashMap<String, Object>();map.put("img", imgId[i]);map.put("name", names[i]);map.put("country", country[i]);listItem.add(map);}// 创建Adapter实例SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, listItem,R.layout.item, new String[] { "img", "name", "country" },new int[] { R.id.Img, R.id.name, R.id.country });ListView listView = (ListView) findViewById(R.id.listViewId);listView.setAdapter(adapter);// 为listView设置Adapter}}


 
原创粉丝点击