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

Android 控件開發實戰:ListView 入門到上手

編輯:關於 Android 程式設計

用 ListView 把數據「排隊」展示給用戶

在 Android 早期開發裡,ListView 幾乎是列表類界面的標配。它能把一批同結構的數據(聯繫人、聊天記錄、菜單項)以可滾動、可復用的方式鋪排在屏幕上。本文以一個「展示用戶名稱與 IP」的小例子,把 ListView 的完整使用鏈路走一遍:數據準備 → 佈局搭建 → 適配器綁定 → 事件響應。

一、整體思路

ListView 本身不關心數據長什麼樣,它只負責「滾動 + 回收」。真正決定每一行外觀的是三樣東西:

  • 數據源:這裡用 ArrayList<HashMap<String, String>>,每個 Map 代表一行;
  • 行佈局:單獨寫一個 user.xml,描述一行裡有幾個 TextView;
  • 適配器:把數據和行佈局「對接」起來,本例使用最省事的 SimpleAdapter。

Activity 直接繼承 ListActivity,這樣可以少寫一行 findViewById,用 setListAdapter() 即可完成綁定。

二、Activity 代碼

package com.example.listview;

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

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 1. 準備數據:list 的每一個元素都是一個 map,代表列表中的一行
        ArrayList<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>();

        // 2. 往 map 中放入鍵值對,key 需要和佈局中的 id、適配器的映射保持一致
        map1.put("name", "zhangsan");
        map1.put("ip", "192.168.1.1");
        map2.put("name", "lisi");
        map2.put("ip", "192.168.1.2");
        map3.put("name", "wangwu");
        map3.put("ip", "192.168.1.3");

        // 3. 把每一行裝進 list
        list.add(map1);
        list.add(map2);
        list.add(map3);

        // 4. 生成適配器:指定行佈局,以及「數據 key」與「控件 id」的對應關係
        SimpleAdapter adapter = new SimpleAdapter(
                this,
                list,
                R.layout.user,
                new String[]{"name", "ip"},
                new int[]{R.id.name, R.id.ip});

        setListAdapter(adapter);
    }

    // 單擊某一行時回調,position 是位置,id 是行數據的標識
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        System.out.println("position = " + position + " , id = " + id);
    }
}

這裡有一個容易踩的坑:SimpleAdapter 構造函數中的 new int[]{R.id.name, R.id.ip} 必須與 new String[]{"name", "ip"} 一一對應,順序錯了不會報錯,但界面上的文字會「串行」。

三、主佈局 main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    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=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/listLinearLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ListView
            android:id="@id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="false"
            android:scrollbars="vertical" />
    </LinearLayout>
</LinearLayout>

使用 ListActivity 時,ListView 的 id 有約定:寫成 @id/android:list,系統會自動找到它。若使用普通 Activity,則可自行命名,再用 findViewById 獲取。

四、行佈局 user.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/mapLinear"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/name"
        android:layout_width="180dip"
        android:layout_height="30dip"
        android:textSize="20dip"
        android:gravity="center_vertical" />

    <TextView
        android:id="@+id/ip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dip" />
</LinearLayout>

行佈局採用水平方向的 LinearLayout,左側固定寬度放名稱,右側 fill_parent 放 IP,這樣無論文字長短都不會互相擠壓。

五、效果與小結

運行後可以看到三行「名稱 + IP」的列表,點擊任意一行,控制台會打印出對應的 position 與 id。

回顧整個流程,ListView 的三件套缺一不可:數據源決定內容,行佈局決定樣式,適配器負責粘合。掌握了這條主線之後,當 SimpleAdapter 無法滿足複雜交互(例如每行帶圖片、按鈕、異步加載)時,就可以自然過渡到自定義 BaseAdapter,並配合 convertView 復用與 ViewHolder 模式做性能優化。

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