Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 通用 ListView 適配器封裝與 ViewHolder 優化

編輯:關於 Android 程式設計

為什麼需要通用適配器

ListView 是 Android 開發中非常常見的列表控制項。若每個列表都重複撰寫 Adapter 與 ViewHolder,會讓程式碼冗長且難以維護。透過通用 Adapter 與 ViewHolder,可以大幅減少樣板程式碼。

CommonAdapter 的關鍵,是把資料、布局與 ViewHolder 綁定在一起。子類別只需要實作 convert 方法,決定每個項目要如何顯示。

CommonAdapter 範例

public abstract class CommonAdapter<T> extends BaseAdapter {
  private Context context;
  private List<T> datas;
  private int layoutId;
  private LayoutInflater inflater;

  public CommonAdapter(Context context, List<T> datas, int layoutId) {
    this.context = context;
    this.datas = datas;
    this.layoutId = layoutId;
    this.inflater = LayoutInflater.from(context);
  }

  @Override
  public int getCount() {
    return datas == null ? 0 : datas.size();
  }

  @Override
  public Object getItem(int position) {
    return datas.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = ViewHolder.get(context, convertView, parent, layoutId, position);
    convert(holder, (T) getItem(position));
    return holder.getConvertView();
  }

  public abstract void convert(ViewHolder holder, T data);
}

ViewHolder 的作用

ViewHolder 的作用,是快取 item 布局中的子 View,避免 getView 中重複 findViewById。它通常會把 convertView 與自身綁定,並用 SparseArray 保存已找到的 View。

public class ViewHolder {
  private final SparseArray<View> views = new SparseArray<>();
  private View convertView;
  private int position;

  public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
    this.convertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
    this.convertView.setTag(this);
    this.position = position;
  }

  public static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId, int position) {
    if (convertView == null) {
      return new ViewHolder(context, parent, layoutId, position);
    }
    ViewHolder holder = (ViewHolder) convertView.getTag();
    holder.position = position;
    return holder;
  }

  public View getConvertView() {
    return convertView;
  }

  public int getPosition() {
    return position;
  }

  public <T extends View> T getView(int id) {
    View view = views.get(id);
    if (view == null) {
      view = convertView.findViewById(id);
      views.put(id, view);
    }
    return (T) view;
  }

  public ViewHolder setText(int id, String text) {
    TextView textView = getView(id);
    textView.setText(text);
    return this;
  }
}

使用方式

使用時,自定義 Adapter 繼承 CommonAdapter,並在 convert 中設定文字、圖片或監聽器。若列表項目包含 CheckBox 等狀態控制項,記得把狀態寫回資料物件,避免回收後顯示錯亂。

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