package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListViewTest extends Activity {
/** Called when the activity is first created. */
ListView listview = null;
SimpleAdapter adapter = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
ArrayList<String> list1 = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView)findViewById(R.id.listview);
//注意点android.R.layout.simple_list_item_2用的android自带的layout,那么new int[]{android.R.id.text1,android.R.id.text2}也必须用android中的控件,自定义的layout不能和android中自带的控件混用。
adapter = new SimpleAdapter(this,list,android.R.layout.simple_list_item_2,new String[]{"text2","text1"},new int[]{android.R.id.text1,android.R.id.text2}); //这里使用的是android自带的layout和TextView控件
//adapter = new SimpleAdapter(this,list,R.layout.view,new String[]{"text2","text1"},new int[]{R.id.textview1,R.id.textview2});//这里使用的自定义的layout和TextView控件
getList();
listview.setAdapter(adapter);
}
public void getList()
{
HashMap<String,String> map1 =new HashMap<String,String>();
map1.put("text1", "pfg");
map1.put("text2", "lhy");
HashMap<String,String> map2 =new HashMap<String,String>();
map2.put("text1", "hyt");
map2.put("text2", "grp");
HashMap<String,String> map3 =new HashMap<String,String>();
map3.put("text1", "klt");
map3.put("text2", "dfg");
HashMap<String,String> map4 =new HashMap<String,String>();
map4.put("text1", "fgh");
map4.put("text2", "bht");
HashMap<String,String> map5 =new HashMap<String,String>();
map5.put("text1", "lky");
map5.put("text2", "wqp");
HashMap<String,String> map6 =new HashMap<String,String>();
map6.put("text1", "htg");
map6.put("text2", "jhp");
list.add(map1);
list.add(map2);
list.add(map3);
list.add(map4);
list.add(map5);
list.add(map6);
//adapter.notifyDataSetChanged();
}
}
XML文档如下:
(1)main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
(2)view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
/>
<TextView
android:id="@+id/textview2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
>
</TextView>
</LinearLayout>