首先定義主Actvity的顯示佈局XML文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ListView
android:id="@+id/mylist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></ListView>
</LinearLayout>
添加到列表中的每個元素都叫item,爲每個item定義佈局格式文件:simple_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
/>
<LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#f0f"
android:paddingLeft="10dp"
/>
<TextView
android:id="@+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dp"
android:paddingLeft="10dp"
/>
</LinearLayout>
</LinearLayout>
定義主testActivity,並添加監聽器
public class SimpleAdapterTest extends Activity{
//測試列表適配器,列表中的每一項都是圖像和兩個textview
private String[] names=new String[]{"虎頭","弄玉","李清照","李白"};
private String[] descs=new String[]{"可愛的女孩","一個擅長音樂的女孩","一個擅長文學的女性","浪漫主義詩人"};
private int[] imageIds=new int[]{R.drawable.tiger,R.drawable.nongyu,R.drawable.qingzhao,R.drawable.libai};
@Override
public void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.main);
List<Map<String, Object>> listItems=new ArrayList<Map<String,Object>>();
for (int i = 0; i < names.length; i++) {
Map<String, Object> listItem=new HashMap<String,Object>();
listItem.put("header", imageIds[i]);
listItem.put("personName", names[i]);
listItem.put("desc",descs[i]);
listItems.add(listItem);
}
SimpleAdapter simpleAdapter=new SimpleAdapter(this, listItems, R.layout.simple_item, new String[]{"personName","header","desc"}, new int[]{R.id.name,R.id.header,R.id.desc});
ListView list=(ListView)findViewById(R.id.mylist);
list.setAdapter(simpleAdapter);
//list.setOnItemClickListener(new OnItemClickListener() {
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position,
// long id) {
//
// Toast.makeText(SimpleAdapterTest.this, names[position]+"被點擊了", Toast.LENGTH_LONG).show();
// }
//});
list.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
//Toast.makeText(SimpleAdapterTest.this, names[position]+"被選中",Toast.LENGTH_LONG).show();
System.out.println(names[position]+"被選中。。。。。");
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}