Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

ArrayAdapter 與 BaseAdapter 該怎麼選

編輯:進階開發

不少開發者搞不清楚 ArrayAdapter 與 BaseAdapter 的關係。簡單說:ArrayAdapter 是從 BaseAdapter 派生出來的,具備 BaseAdapter 的所有功能,但更強大。

泛型與建構方式

ArrayAdapter 支援泛型,SDK 中可見 android.widget.ArrayAdapter<T> 這樣的宣告。也可以用 ArrayAdapter(Context context, int textViewResourceId) 直接綁定一個 layout。

自訂列表項

實務上常需要自訂每一列的樣式。以下範例展示如何繼承 ArrayAdapter 並在 getView 中載入自訂版面:

public class IconListAdapter extends ArrayAdapter<IconListAdapter.IconListItem> {
先宣告 protected LayoutInflater mInflater; 與版面資源 id,在建構子中呼叫 super(context, mResource, items),並以 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) 取得 inflater。

接著重載 getView(int position, View convertView, ViewGroup parent):若 convertView 為 null 就 inflate 新的 View,否則直接複用(這就是所謂的 View 回收機制,是列表效能的關鍵)。然後用 findViewById() 取出 TextView 與 ImageView,分別設定文字與圖示即可。

補充一個技巧:如果你不想額外放 ImageView,TextView 本身也能顯示圖示,用 setCompoundDrawables() 或 setCompoundDrawablesWithIntrinsicBounds() 就能在文字的左、上、右、下指定 Drawable;其中 int 參數版本接受的是資源 id。

ArrayAdapter 的獨門工具

從名稱就能聯想到它與陣列操作密切相關。幾個實用方法:

add(T object) 加入一筆;clear() 清空;insert(T object, int index) 在指定位置插入;remove(T object) 移除;getPosition(T item) 由物件反查位置;sort(Comparator) 直接排序,相當方便;createFromResource() 可從字串陣列資源直接建構;getFilter() 提供正則表達式過濾。

最值得推薦的是 setNotifyOnChange(boolean)。它能暫停 add、insert、remove、clear 這些操作的自動通知,改由你在批次處理完之後,用 notifyDataSetChanged() 或 setNotifyOnChange(true) 統一通知。處理大量資料時,這能大幅降低 UI 的刷新次數。

結論

資料量大(例如超過一百筆)或需要頻繁動態增減時,用 ArrayAdapter 搭配 setNotifyOnChange 更好控制 UI 刷新節奏。若只是單純呈現少量靜態資料,直接從 BaseAdapter 派生反而更省資源。

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