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

關於 Android ListView 的基礎用法詳解

編輯:關於 Android 程式設計

最近參與的一個專案需要呈現一個包含標題與內容的列表頁面。過去雖然用過 ListView,但當時的資料是從手機本地資料庫讀取的;這次資料來源換成了公司 PHP 網站的伺服器,原先使用的 SimpleCursorAdapter 似乎不再適用。翻了一些網路上的範例程式碼後,我心裡一直有個疑惑:他們寫的 ListActivity 子類幾乎都沒有呼叫 setContentView,那到底呈現的是什麼畫面呢?這讓我頗為不解。後來自己動手實驗才發現,原來不特別指定時,顯示的就是這個子類本身。

下面是一個使用 ListActivity 搭配 SimpleAdapter 的完整範例:

 package com.example.listview;

 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import android.os.Bundle;
 import android.app.ListActivity;
 import android.widget.SimpleAdapter;

 public class MyListView3 extends ListActivity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.vlist,
                 new String[]{"title", "info"}, new int[]{R.id.title, R.id.info});
         setListAdapter(adapter);
     }

     private List<Map<String, Object>> getData() {
         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
         Map<String, Object> map = new HashMap<String, Object>();
         map.put("title", "G1");
         map.put("info", "google 1");
         list.add(map);
         map = new HashMap<String, Object>();
         map.put("title", "G2");
         map.put("info", "google 2");
         list.add(map);
         map = new HashMap<String, Object>();
         map.put("title", "G3");
         map.put("info", "google 3");
         list.add(map);
         return list;
     }
 }

與之搭配的列表項佈局 vlist.xml 如下:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:layout_height="fill_parent"
     android:layout_width="fill_parent"
     android:orientation="horizontal">
     <TextView
         android:id="@+id/title"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:textSize="22px" />
     <TextView
         android:id="@+id/info"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:textSize="13px" />
 </LinearLayout>

運行效果如下圖所示:

關鍵在於:由於 ListActivity 預設本身就帶有一個 ListView,因此只要透過 setListAdapter 綁定資料,無需再自行呼叫 setContentView 指定佈局,畫面便會自動呈現列表內容。

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