ArrayAdapter和SimpleAdapter
ArrayAdapter只能处理一种数据,this是上下文对象,layout是布局文件,tv_name是准备显示的资源的id,objects是显示的字符String数组
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.item_listview, R.id.tv_name,objects));
布局文件
activity_main.xml
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
item_listView.xml
<?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" >
<TextView
android:id="@+id/tv_pic"
android:layout_height="30px"
android:layout_width="30px"
android:text="O"
/>
<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"
></TextView>
</LinearLayout>
逻辑代码
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] objects = new String[]{
"AAAA",
"BBBB",
"CCCC"
};
ListView lv = (ListView) findViewById(R.id.lv);
//ArrayAdapter使用
//lv.setAdapter(new ArrayAdapter<String>(this, R.layout.item_listview, R.id.tv_name,objects));
//SimpleAdapter支持多种数据
//集合中每个元素包含ListView条目所需要的数据,每个条目包含一个字符串和一个整型,使用map封装这2数据
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("photo", "aaaa");
map1.put("name", "AAAA");
data.add(map1);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("photo", "cccc");
map2.put("name", "CCCC");
data.add(map2);
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("photo", "bbbb");
map3.put("name", "BBBB");
data.add(map3);
Map<String, Object> map4 = new HashMap<String, Object>();
map4.put("photo", "dddd");
map4.put("name", "DDDD");
data.add(map4);
lv.setAdapter(new SimpleAdapter(this, data, R.layout.item_listview,
new String[]{"photo", "name"}, new int[]{R.id.tv_pic, R.id.tv_name}
));
}