ListView的使用

首先创建一个布局文件作为ListView列表项组件

<?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="match_parent"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/textViewI"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/textViewII"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

在界面布局中定义一个ListView

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

在程序代码中创建一个List集合,List集合的元素是Map

        List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
        Map<String, Object> map=new HashMap<String, Object>();        
        map.put("key", "value");
        list.add(map);

使用SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)方法创建一个SimpleAdapter 

        SimpleAdapter simpleAdapter=new SimpleAdapter(this,list,R.layout.list,
                new String[]{"keyI","keyII"},new int[]{R.id.textViewI,R.id.textViewII});

为ListView设置Adapter

        listView.setAdapter(simpleAdapter);

通过setOnItemClickListener()方法为单击事件添加监听器

        listView.setOnItemClickListener(new OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                
            }});
position The position of the view in the adapter.
id The row id of the item that was clicked.

 

 

 

posted on 2013-12-04 10:59  张茂晨  阅读(195)  评论(0编辑  收藏  举报