android 71 ArrayAdapter和SimpleAdapter
Activity和item:
Activity:
<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="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> item: <?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/iv_photo" android:layout_width="40dp" android:layout_height="40dp" android:src="@drawable/photo3" /> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="名字" android:textSize="22sp" android:layout_gravity="center_vertical" /> </LinearLayout>
java:
package com.itheima.arraysimple; 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.ArrayAdapter; 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); String[] objects = new String[]{ "小志", "小志的儿子", "萌萌" }; ListView lv = (ListView) findViewById(R.id.lv); //ArrayAdapter只能够处理一种数据类型String,做了高度的封装。 lv.setAdapter(new ArrayAdapter<String>(this, R.layout.item_listview, R.id.tv_name, objects)); //集合中每个元素都包含ListView条目需要的所有数据,该案例中每个条目需要一个字符串和一个整型,所以使用一个map来封装这两种数据 List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("photo", R.drawable.photo1); map1.put("name", "小志的儿子"); data.add(map1); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("photo", R.drawable.photo2); map2.put("name", "小志"); data.add(map2); Map<String, Object> map3 = new HashMap<String, Object>(); map3.put("photo", R.drawable.photo3); map3.put("name", "赵帅哥"); data.add(map3); //SimpleAdapter,item_listview是item, //new String[]{"photo", "name"}, new int[]{R.id.iv_photo, R.id.tv_name}指定photo放入R.id.iv_photo组件,name放入R.id.tv_name组件 lv.setAdapter(new SimpleAdapter(this, data, R.layout.item_listview, new String[]{"photo", "name"}, new int[]{R.id.iv_photo, R.id.tv_name})); } }