編輯:關於 Android 程式設計
ListView 的適配器有好幾種:ArrayAdapter、BaseAdapter、SimpleAdapter 等等。本篇先熱身,用最簡單的 SimpleAdapter 把資料呈現出來。
先在 activity_main.xml 放一個 ListView:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
再為每個列表項準備一個版面檔 item_listview.xml。這裡放一張圖片加一段文字:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_photo"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/photo3" />
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="22sp" />
</LinearLayout>
SimpleAdapter 要求資料以「List<Map>」的形式提供:每個 Map 代表一列,key 對應版面中的控制項,value 是實際要顯示的內容。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.lv);
// 每個 Map 對應一個列表項,封裝該項需要的所有資料
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("photo", R.drawable.photo1);
map1.put("name", "小志的兒子");
data.add(map1);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("photo", R.drawable.photo2);
map2.put("name", "小志");
data.add(map2);
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("photo", R.drawable.photo3);
map3.put("name", "趙帥哥");
data.add(map3);
lv.setAdapter(new SimpleAdapter(
this,
data,
R.layout.item_listview,
new String[]{"photo", "name"}, // from:Map 的 key
new int[]{R.id.iv_photo, R.id.tv_name} // to:目標控制項 id
));
}
}
SimpleAdapter 的建構子參數依序是:Context、資料來源、item 版面 id、from、to。這裡最容易出錯的就是 from 與 to:

SimpleAdapter 適合版面固定、資料單純的場景。但一旦需要「依資料內容動態改變樣式」、「為不同型別的項目使用不同版面」,或「只更新其中一項而不重繪全部」,它就顯得力不從心——那時就該換成繼承 BaseAdapter 自訂 Adapter,並搭配 ViewHolder 模式來複用 convertView。
Retrofit 入門到進階:用注解把網路請求寫成介面
先前整理過 OkHttp 與 Volley,這個系列的最後一篇留給 Retrofit。可以把它理解為 OkHttp 的「升級版」——它內部預設就是基於 OkHttp 封裝
Android App 線上更新的完整實作流程
線上更新是幾乎每個 App 都需要的功能。本文以一個完整的 Splash 啟動頁為例,把「檢查版本 → 提示更新 → 下載 APK → 觸發安裝」這條鏈路走一遍。 一、
紅米Note4發表了嗎?海報洩漏的雙鏡頭新機線索
小米日前曝光的一張宣傳海報裡,紅米新代言人劉昊然手上拿著一支手機,低頭看不太出全貌,但有一個細節很清楚:背面是雙鏡頭。這支機器不對應任何已發表的型號,於是外界推測它就是尚
Android HandlerThread 全面解析:Looper、Message 與 IntentService
在 Android 中,UI 更新通常需要在主執行緒進行,但耗時工作若也放在主執行緒,容易造成畫面卡頓。HandlerThread 的價值,就是把 Looper 與 Ha