編輯:關於 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>
基本思路是:先將資料加入 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,將資料以列表形式呈現。
微信電腦版誤發訊息怎麼辦?撤回功能操作教學
微信電腦版可撤回誤發訊息。在聊天視窗中找到訊息,按右鍵選擇撤回,對話中會顯示已撤回提示。 此功能可減少打錯字或傳錯檔案的困擾。
我的 Android 進階之旅:解決 Android 5.0 的「Service Intent must be explicit」崩潰
1. 錯誤描述 同一份程式碼,在 Android 4.4 的小米 4 上跑得好好的,換到 Android 5.1 的華為 P7 上卻直接閃退。Logcat 給出的訊息是:
Android Studio 安裝與更新卡關的完整解法
先前寫過一篇 Android SDK 無法更新的處理方式,那套思路對 Android Studio 同樣有效。這篇把安裝過程中常見的卡點與對策整理成一份可直接照做的清單。
Unity3D 數字模型製作規範
本文所述的數字模型製作均以 3ds Max 完成。即便最終驅動引擎不同,對模型的基本要求是大體一致的。一個 VR 模型交付時,其場景尺寸與單位、模型歸類與塌陷、命名、節點