編輯:關於 Android 開發
ListView 一定要配 Adapter 才能動,而 Adapter 有兩條路:ArrayAdapter 只能顯示單純文字,SimpleAdapter 則能把文字與圖片一起塞進自訂布局。如果畫面上有圖,基本上就是 SimpleAdapter 的場子。
SimpleAdapter 的建構子看起來很嚇人,其實每一格都有明確分工:
SimpleAdapter(context, data, resource, from, to)
List<Map<String, Object>>,List 的每一項代表一列,每個 Map 則是該列的「欄位名稱 → 值」對照表。from 與 to 是一一對應的關係,兩邊的順序與數量必須一致,這是新手最常出錯的地方。
放在 res/layout 底下:
<?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"> <ImageView android:id="@+id/itempic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:src="@mipmap/ic_launcher" /> <TextView android:id="@+id/itemtext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="demo" android:textSize="40sp" /> </LinearLayout>
這裡刻意給兩個子元件都加上 id,因為 to 陣列就是靠 id 來定位。
工具:Android Studio
private ListView listView; // private ArrayAdapter<String> adapter; private SimpleAdapter si_adapter; //list集合是抽象集合,實例化其實例對象ArrayList private List<Map<String,Object>> simpleData; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.listView); simpleData=new ArrayList<Map<String,Object>>(); si_adapter=new SimpleAdapter(this,getData(),R.layout.item,new String[]{"pic","text"},new int[]{R.id.itempic,R.id.itemtext}); listView.setAdapter(si_adapter); }
public List<Map<String,Object>> getData(){ for(int i=0;i<20;i++){ Map<String,Object> map=new HashMap<String,Object>(); //填入真實的pic信息 map.put("pic",R.mipmap.ic_launcher); //填入真實的text信息 map.put("text","機器人"+i+"號"); simpleData.add(map); } return simpleData; }
注意 map.put("pic", R.mipmap.ic_launcher) 這行:SimpleAdapter 的圖片欄位可以直接放 drawable/mipmap 的資源 ID(int),也可以放 Bitmap 或 File 物件,甚至自訂 ImageView 都能吃。這是它比 ArrayAdapter 強的地方。
整個機制其實是一場對照遊戲:
SimpleAdapter 的致命弱點是效能。它內部靠反射把值塞進 view,而且每次 getView 都被呼叫時都要重新走一遍流程,同時它不會幫你做 convertView 複用。列表一長,掉幀很明顯。
所以判斷標準很簡單:資料超過一二十列、單列布局有點複雜、或需要快取與非同步載圖,就該果斷換成繼承 BaseAdapter 自己寫 getView。SimpleAdapter 適合的是那種「數量固定、結構單純、快速做個 demo」的場合。理解它的對照邏輯有價值,但別讓它進 production。
SharedPreferences 輕量級資料儲存:以記住音樂播放進度為例
Android 在資料儲存與資料共享上提供了多種手段,前面我們已經講過用 SQLite 資料庫的方式。這一節要介紹的是另一條更輕巧的路——共享參數類 SharedPref
Android Studio 下的 NDK 開發全流程:從 javah 到 loadLibrary 的踩坑記錄
早年做 NDK 開發基本都在 Eclipse 環境下折騰,流程相對直觀。換到 Android Studio 之後,很多原本習以為常的步驟都變了樣,classpath、生成
Android 手機衛士實作教學(一):打造 Splash 啟動頁
Android 手機衛士實作教學(一):打造 Splash 啟動頁 1. minSdkVersion、targetSdkVersion、maxSdkVersion、ta
ActionBar 使用完整指南:主題設定、菜單屬性與返回鍵處理
在 Android Studio 專案中使用 ActionBar 1、在清單檔中指定主題 要啟用 ActionBar,主題必須是 Theme.Holo 或其子類: <