Android开发之ListView-SimpleAdapter的使用

时间:2023-03-10 05:25:58
Android开发之ListView-SimpleAdapter的使用

SimpleAdapter:

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

参数:

1.context:上下文

2.data:Map<String, object>列表,列表要显示的数据,Map列表中的key要与参数”from“中的内容保持一致

3.resource:item的布局文件,这个布局中必须包括参数”to“中定义的控件id

4.from:表示该Map对象的key对应value来生成列表项

5.to:表示来填充的组件 Map对象key对应的资源一依次填充组件 顺序有对应关系

ListView的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 ListView lv; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); List<Map<String, Object>> data = new ArrayList<>(); Map<String, Object> map1 = new HashMap<>();
map1.put("photo", R.drawable.img01);
map1.put("name", "小志");
data.add(map1); Map<String, Object> map2 = new HashMap<>();
map2.put("photo", R.drawable.img02);
map2.put("name", "小志的儿子");
data.add(map2); Map<String, Object> map3 = new HashMap<>();
map3.put("photo", R.drawable.img03);
map3.put("name", "小志的老婆");
data.add(map3); Map<String, Object> map4 = new HashMap<>();
map4.put("photo", R.drawable.img04);
map4.put("name", "萌萌");
data.add(map4); lv = (ListView) findViewById(R.id.lv); lv.setAdapter(new SimpleAdapter(this, data, R.layout.item_view,
new String[] { "photo", "name" }, new int[] { R.id.lv_phono,
R.id.lv_name })); } }

item_view布局文件:

 <?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="wrap_content"
android:orientation="horizontal" > <ImageView
android:id="@+id/lv_phono"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/img01" /> <TextView
android:id="@+id/lv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="名字"
android:textSize="20sp" /> </LinearLayout>
activity_main布局文件:
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" > <ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView> </RelativeLayout>