編輯:關於 Android 程式設計
ListView 是 Android 最歷史悠久的垂直列表元件。它本身只負責「怎麼排」,資料怎麼來、每一列長什麼樣,交給 Adapter 與資料集決定——這正是典型 MVC 的分工方式。
第一種直接在配置檔放 <ListView> 標籤,於 Activity 中 findViewById 取得;第二種讓 Activity 繼承 ListActivity,用 setListAdapter() 直接餵資料。新手建議先用第一種,控制力比較直觀。
android:entries:直接指定一個字串陣列資源,Android 會自動幫你生出一份清單,最省事的寫法。android:divider:設定列表項之間的分隔線,顏色或 Drawable 都可以。這裡刻意把 ListView 與用來呈現內容的 ImageView、TextView 並列在 LinearLayout 中,而不是把子檢視塞進 ListView 內部——原因後面會說明。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20sp" />
</LinearLayout>
SimpleAdapter 的做法是把資料整理成一串 Map,再告訴它「哪個 key 對應哪個 View」。
ListView listView = (ListView) findViewById(R.id.list);
List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
for (int i = 0; i < names.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", names[i]);
map.put("image", images[i]);
maps.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, maps, R.layout.item,
new String[] { "name", "image" },
new int[] { R.id.textView, R.id.imageView });
listView.setAdapter(adapter);
List<Map<String, ?>>,每個 Map 產生一列。一開始把 ImageView、TextView 直接寫在 ListView 標籤內部,執行時丟出:
java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
原因在於 AdapterView 系列不允許 arbitrary 的子檢視寫在配置檔裡,它的內容必須由 Adapter 產生。正確觀念是:ListView 只留一個空殼,真正用來顯示單列內容的版面另外開一個配置檔,再交給 Adapter 指定。養成這個習慣,後面換成 BaseAdapter 自訂一列樣式時也會順很多。
自定義 Android EditText 背景與輸入驗證
用 layer-list 建立背景EditText 的背景可以透過 layer-list 與 shape 定義。使用 solid 設定填充色,stroke 設定邊框,co
Android 時間處理與同步:時區、伺服器時間與 SystemClock 實務
Android 時間處理的常見問題在 Android 應用中,時間顯示看似簡單,實際上卻經常出問題。使用者可能手動修改系統時間、切換時區,或裝置時間與伺服器不同步,導致簽
Android GridView 基礎與網格線技巧
GridView 在 Android 開發中經常用於展示多列多行的內容,例如圖片牆、功能入口或選單。本文從最基礎的布局開始,介紹 GridView 的使用方式,並分享一個
Android 事件傳遞機制深度剖析:從源碼看事件分發與沖突處理
已經有一段時間沒寫部落格了,最近忙著趕專案,也有些迷茫不知道該寫什麼。正好最近遇到一個自訂控件的事件沖突問題,於是上網找了很多關於事件傳遞與事件沖突的解決方案,再結合 A