第一步:在布局檔案中添加<ListView>元件
<LinearLayout 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:orientation="vertical"
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="com.shensu.adapter.MainActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:text="姓名"
android:gravity="center"
android:textColor="#ff0000"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
<TextView
android:text="電話"
android:gravity="center"
android:textColor="#ff0000"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
<TextView
android:text="薪水"
android:gravity="center"
android:textColor="#ff0000"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
></ListView>
</LinearLayout>
第二步:在Activity中擷取listView元件
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
lv = (ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {//parent:被點選條目所在的listView view:被點選的條目
//position:目前被點選條目所綁定資料在集合中的索引值, id:目前被點選條目在listView中的id值
ListView lView = (ListView)parent;
Person person = (Person) lView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, person.getName(), 0).show();
}
});
show2();
}
第三步:為listView添加SimpleAdapter擴充卡
private void show() {
List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
for(int i=0;i<20;i++){
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("name", "zhangsan_"+i);
map.put("phone", "795150_"+i);
map.put("salary", "2000_"+i);
list.add(map);
}
//arg0:上下文, arg1:要填充的資料 arg2:指定要填充到哪個布局檔案布局檔案
//arg3:填充資料map的key值 arg4:資料填充到布局檔案中的哪個View對象
SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.listview_item,
new String[]{"name","phone","salary"}, new int[]{R.id.name,R.id.phone,R.id.salary});
lv.setAdapter(simpleAdapter);
}