Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發系列(五):ListView 基礎用法入門

編輯:關於 Android 程式設計

初次接觸 Android 開發時曾學過 ListView 的基礎用法,时间久了容易忘記,這裡做一次系統性的整理。本文先介紹最基本的 ListView 用法,下一篇再說明如何透過繼承 BaseAdapter 實現功能更完整的 ListView。

佈局檔案

需要兩個佈局檔案:一個是 Activity 對應的 main.xml,另一個是 ListView 每一行所使用的 list_item.xml。

此處需注意:ListView 控件的 id 要使用系統內建的 android:id="@android:id/list"。

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="20dip"/>
</LinearLayout>

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/user_name"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/user_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>

MainActivity 程式碼

基本思路是:先將資料加入 ArrayList,再透過 SimpleAdapter 完成綁定。

package com.example.android_newlistview;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.app.ListActivity;

public class MainActivity extends ListActivity {
    String[] from = {"name", "id"};   // ListView 每一列的列名
    int[] to = {R.id.user_name, R.id.user_id}; // 對應 list_item 中控件的 id
    String[] userName = {"zhangsan", "lisi", "wangwu", "zhaoliu"};
    String[] userId = {"1001", "1002", "1003", "1004"};

    ArrayList<HashMap<String,String>> list = null;
    HashMap<String,String> map = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list = new ArrayList<HashMap<String,String>>();
        // ListView 的一行資料對應一個 HashMap,以列名為鍵、該列的值為 Value
        for(int i = 0; i < 4; i++){
            map = new HashMap<String,String>(); // 有幾列就建立幾個 map,避免空指標
            map.put("id", userId[i]);
            map.put("name", userName[i]);
            list.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.list_item, from, to);
        setListAdapter(adapter); // 為 ListView 設定適配器
    }
}

透過以上步驟,即可實現一個基礎的 ListView,將資料以列表形式呈現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved