Android中ListView的使用

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"
    >
    <LinearLayout    android:id="@+id/listLinearLayout"
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
            <ListView    android:id="@id/android:list"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:drawSelectorOnTop="false"></ListView>
    </LinearLayout>
</LinearLayout>

 

listview.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    >
    <TextView    android:id="@+id/user_name"
                android:layout_width="180dip"
                android:layout_height="30dip"></TextView>
      <TextView    android:id="@+id/user_phone"
                android:layout_width="180dip"
                android:layout_height="30dip"
                android:gravity="right"></TextView>
</LinearLayout>

 

2、加載數據(請注意:頁面類繼承的不是Activity而是ListActivity類)

package yyl.listview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleAdapter;

public class ListViewActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map1 = new HashMap<String, String>();
        HashMap<String, String> map2 = new HashMap<String, String>();
        HashMap<String, String> map3 = new HashMap<String, String>();

        map1.put("user_name", "abcdddd");
        map1.put("user_phone", "12345454455");
        map2.put("user_name", "abcdddd");
        map2.put("user_phone", "12345454455");
        map3.put("user_name", "abcdddd");
        map3.put("user_phone", "12345454455");   

        list.add(map1);
        list.add(map2);
        list.add(map3);

        SimpleAdapter adapter = new SimpleAdapter(ListViewActivity.this, list,
                R.layout.listitem, new String[] { "user_name", "user_phone" },
                new int[] { R.id.user_name, R.id.user_phone });
        setListAdapter(adapter);

    }

}

 

發佈了36 篇原創文章 · 獲贊 5 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章