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的使用
代码:
1 import java.util.ArrayList; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 6 import android.app.Activity; 7 import android.os.Bundle; 8 import android.widget.ListView; 9 import android.widget.SimpleAdapter; 10 11 public class MainActivity extends Activity { 12 13 private ListView lv; 14 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 setContentView(R.layout.activity_main); 19 20 List<Map<String, Object>> data = new ArrayList<>(); 21 22 Map<String, Object> map1 = new HashMap<>(); 23 map1.put("photo", R.drawable.img01); 24 map1.put("name", "小志"); 25 data.add(map1); 26 27 Map<String, Object> map2 = new HashMap<>(); 28 map2.put("photo", R.drawable.img02); 29 map2.put("name", "小志的儿子"); 30 data.add(map2); 31 32 Map<String, Object> map3 = new HashMap<>(); 33 map3.put("photo", R.drawable.img03); 34 map3.put("name", "小志的老婆"); 35 data.add(map3); 36 37 Map<String, Object> map4 = new HashMap<>(); 38 map4.put("photo", R.drawable.img04); 39 map4.put("name", "萌萌"); 40 data.add(map4); 41 42 lv = (ListView) findViewById(R.id.lv); 43 44 lv.setAdapter(new SimpleAdapter(this, data, R.layout.item_view, 45 new String[] { "photo", "name" }, new int[] { R.id.lv_phono, 46 R.id.lv_name })); 47 48 } 49 50 }
item_view布局文件:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="wrap_content" 5 android:orientation="horizontal" > 6 7 <ImageView 8 android:id="@+id/lv_phono" 9 android:layout_width="60dp" 10 android:layout_height="60dp" 11 android:src="@drawable/img01" /> 12 13 <TextView 14 android:id="@+id/lv_name" 15 android:layout_width="wrap_content" 16 android:layout_height="wrap_content" 17 android:layout_gravity="center_vertical" 18 android:text="名字" 19 android:textSize="20sp" /> 20 21 </LinearLayout>
activity_main布局文件:
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context=".MainActivity" > 6 7 <ListView 8 android:id="@+id/lv" 9 android:layout_width="match_parent" 10 android:layout_height="match_parent" > 11 </ListView> 12 13 </RelativeLayout>
时间: 2024-12-17 10:44:35