[关闭]
@coder-pig 2015-09-22T12:29:11.000000Z 字数 10729 阅读 999

Android基础入门教程——2.4.7 构建一个可复用的自定义BaseAdapter

Android基础入门教程


本节引言:

如题,本节给大家带来的是构建一个可复用的自定义BaseAdapter,我们每每涉及到ListView
GridView等其他的Adapter控件,都需要自己另外写一个BaseAdapter类,这样显得非常麻烦,
又比如,我们想在一个界面显示两个ListView的话,我们也是需要些两个BaseAdapter...
这,程序员都是喜欢偷懒的哈,这节我们就来写一个可复用的自定义BaseAdapter类~


1.我们一点点开始改:

首先我们把上节写的自定义BaseAdapter贴下,等下我们就要对他进行升级改造

  1. /**
  2. * Created by Jay on 2015/9/21 0021.
  3. */
  4. public class MyAdapter extends BaseAdapter {
  5. private Context mContext;
  6. private LinkedList<Data> mData;
  7. public MyAdapter() {
  8. }
  9. public MyAdapter(LinkedList<Data> mData, Context mContext) {
  10. this.mData = mData;
  11. this.mContext = mContext;
  12. }
  13. @Override
  14. public int getCount() {
  15. return mData.size();
  16. }
  17. @Override
  18. public Object getItem(int position) {
  19. return null;
  20. }
  21. @Override
  22. public long getItemId(int position) {
  23. return position;
  24. }
  25. @Override
  26. public View getView(int position, View convertView, ViewGroup parent) {
  27. ViewHolder holder = null;
  28. if (convertView == null) {
  29. convertView = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
  30. holder = new ViewHolder();
  31. holder.img_icon = (ImageView) convertView.findViewById(R.id.img_icon);
  32. holder.txt_content = (TextView) convertView.findViewById(R.id.txt_content);
  33. convertView.setTag(holder);
  34. } else {
  35. holder = (ViewHolder) convertView.getTag();
  36. }
  37. holder.img_icon.setImageResource(mData.get(position).getImgId());
  38. holder.txt_content.setText(mData.get(position).getContent());
  39. return convertView;
  40. }
  41. //添加一个元素
  42. public void add(Data data) {
  43. if (mData == null) {
  44. mData = new LinkedList<>();
  45. }
  46. mData.add(data);
  47. notifyDataSetChanged();
  48. }
  49. //往特定位置,添加一个元素
  50. public void add(int position,Data data){
  51. if (mData == null) {
  52. mData = new LinkedList<>();
  53. }
  54. mData.add(position, data);
  55. notifyDataSetChanged();
  56. }
  57. public void remove(Data data) {
  58. if(mData != null) {
  59. mData.remove(data);
  60. }
  61. notifyDataSetChanged();
  62. }
  63. public void remove(int position) {
  64. if(mData != null) {
  65. mData.remove(position);
  66. }
  67. notifyDataSetChanged();
  68. }
  69. public void clear() {
  70. if(mData != null) {
  71. mData.clear();
  72. }
  73. notifyDataSetChanged();
  74. }
  75. private class ViewHolder {
  76. ImageView img_icon;
  77. TextView txt_content;
  78. }
  79. }

升级1:将Entity设置成泛型

好的,毕竟我们传递过来的Entitiy实体类可能千奇百怪,比如有Person,Book,Wether等,所以我们
将Entity设置成泛型,修改后的代码如下:

  1. public class MyAdapter<T> extends BaseAdapter {
  2. private Context mContext;
  3. private LinkedList<T> mData;
  4. public MyAdapter() {
  5. }
  6. public MyAdapter(LinkedList<T> mData, Context mContext) {
  7. this.mData = mData;
  8. this.mContext = mContext;
  9. }
  10. @Override
  11. public int getCount() {
  12. return mData.size();
  13. }
  14. @Override
  15. public Object getItem(int position) {
  16. return null;
  17. }
  18. @Override
  19. public long getItemId(int position) {
  20. return position;
  21. }
  22. @Override
  23. public View getView(int position, View convertView, ViewGroup parent) {
  24. ViewHolder holder = null;
  25. if (convertView == null) {
  26. convertView = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
  27. holder = new ViewHolder();
  28. holder.img_icon = (ImageView) convertView.findViewById(R.id.img_icon);
  29. holder.txt_content = (TextView) convertView.findViewById(R.id.txt_content);
  30. convertView.setTag(holder);
  31. } else {
  32. holder = (ViewHolder) convertView.getTag();
  33. }
  34. holder.img_icon.setImageResource(mData.get(position).getImgId());
  35. holder.txt_content.setText(mData.get(position).getContent());
  36. return convertView;
  37. }
  38. //添加一个元素
  39. public void add(T data) {
  40. if (mData == null) {
  41. mData = new LinkedList<>();
  42. }
  43. mData.add(data);
  44. notifyDataSetChanged();
  45. }
  46. //往特定位置,添加一个元素
  47. public void add(int position,T data){
  48. if (mData == null) {
  49. mData = new LinkedList<>();
  50. }
  51. mData.add(position, data);
  52. notifyDataSetChanged();
  53. }
  54. public void remove(T data) {
  55. if(mData != null) {
  56. mData.remove(data);
  57. }
  58. notifyDataSetChanged();
  59. }
  60. public void remove(int position) {
  61. if(mData != null) {
  62. mData.remove(position);
  63. }
  64. notifyDataSetChanged();
  65. }
  66. public void clear() {
  67. if(mData != null) {
  68. mData.clear();
  69. }
  70. notifyDataSetChanged();
  71. }
  72. private class ViewHolder {
  73. ImageView img_icon;
  74. TextView txt_content;
  75. }
  76. }

好的,上面我们做的事仅仅是将Data类型换成了泛型T!


升级2:ViewHolder类的升级改造:

我们先来看看前面我们的ViewHolder干了什么?
答:findViewById,设置控件状态;
下面我们想在完成这个基础上,将getView()方法大部分的逻辑写到ViewHolder类里,
这个ViewHolder要做的事:

    1. 定义一个查找控件的方法,我们的思路是通过暴露公共的方法,调用方法时传递过来
      控件id,以及设置的内容,比如TextView设置文本:
      public ViewHolder setText(int id, CharSequence text){文本设置}
    1. 将convertView复用部分搬到这里,那就需要传递一个context对象了,我们把需要获取
      的部分都写到构造方法中!
    1. 写一堆设置方法(public),比如设置文字大小颜色,图片背景等!

好的,接下来我们就来一步步改造我们的ViewHolder类


1)相关参数与构造方法:

  1. public static class ViewHolder {
  2. private SparseArray<View> mViews; //存储ListView 的 item中的View
  3. private View item; //存放convertView
  4. private int position; //游标
  5. private Context context; //Context上下文
  6. //构造方法,完成相关初始化
  7. private ViewHolder(Context context, ViewGroup parent, int layoutRes) {
  8. mViews = new SparseArray<>();
  9. this.context = context;
  10. View convertView = LayoutInflater.from(context).inflate(layoutRes, parent,false);
  11. convertView.setTag(this);
  12. item = convertView;
  13. }
  14. ImageView img_icon;
  15. TextView txt_content;
  16. }

2)绑定ViewHolder与Item

在上面的基础上我们再添加一个绑定的方法

  1. //绑定ViewHolder与item
  2. public static ViewHolder bind(Context context, View convertView, ViewGroup parent,
  3. int layoutRes, int position) {
  4. ViewHolder holder;
  5. if(convertView == null) {
  6. holder = new ViewHolder(context, parent, layoutRes);
  7. } else {
  8. holder = (ViewHolder) convertView.getTag();
  9. holder.item = convertView;
  10. }
  11. holder.position = position;
  12. return holder;
  13. }

3)根据id获取集合中保存的控件

  1. public <T extends View> T getView(int id) {
  2. T t = (T) mViews.get(id);
  3. if(t == null) {
  4. t = (T) item.findViewById(id);
  5. mViews.put(id, t);
  6. }
  7. return t;
  8. }

4) 接着我们再定义一堆暴露出来的方法

  1. /**
  2. * 获取当前条目
  3. */
  4. public View getItemView() {
  5. return item;
  6. }
  7. /**
  8. * 获取条目位置
  9. */
  10. public int getItemPosition() {
  11. return position;
  12. }
  13. /**
  14. * 设置文字
  15. */
  16. public ViewHolder setText(int id, CharSequence text) {
  17. View view = getView(id);
  18. if(view instanceof TextView) {
  19. ((TextView) view).setText(text);
  20. }
  21. return this;
  22. }
  23. /**
  24. * 设置图片
  25. */
  26. public ViewHolder setImageResource(int id, int drawableRes) {
  27. View view = getView(id);
  28. if(view instanceof ImageView) {
  29. ((ImageView) view).setImageResource(drawableRes);
  30. } else {
  31. view.setBackgroundResource(drawableRes);
  32. }
  33. return this;
  34. }
  35. /**
  36. * 设置点击监听
  37. */
  38. public ViewHolder setOnClickListener(int id, View.OnClickListener listener) {
  39. getView(id).setOnClickListener(listener);
  40. return this;
  41. }
  42. /**
  43. * 设置可见
  44. */
  45. public ViewHolder setVisibility(int id, int visible) {
  46. getView(id).setVisibility(visible);
  47. return this;
  48. }
  49. /**
  50. * 设置标签
  51. */
  52. public ViewHolder setTag(int id, Object obj) {
  53. getView(id).setTag(obj);
  54. return this;
  55. }
  56. //其他方法可自行扩展

好的,ViewHolder的改造升级完成~


升级3:定义一个抽象方法,完成ViewHolder与Data数据集的绑定

  1. public abstract void bindView(ViewHolder holder, T obj);

我们创建新的BaseAdapter的时候,实现这个方法就好,另外,别忘了把我们自定义
的BaseAdapter改成abstact抽象的!


升级4:修改getView()部分的内容

  1. @Override
  2. public View getView(int position, View convertView, ViewGroup parent) {
  3. ViewHolder holder = ViewHolder.bind(parent.getContext(), convertView, parent, mLayoutRes
  4. , position);
  5. bindView(holder,getItem(position));
  6. return holder.getItemView();
  7. }

2.升级完毕,我们写代码来体验下:

我们要实现的效果图:

就是上面有两个列表,布局不一样,但是我只使用一个BaseAdapter类来完成上述效果!

关键代码如下:

MainActivity.java

  1. public class MainActivity extends AppCompatActivity {
  2. private Context mContext;
  3. private ListView list_book;
  4. private ListView list_app;
  5. private MyAdapter<App> myAdapter1 = null;
  6. private MyAdapter<Book> myAdapter2 = null;
  7. private ArrayList<App> mData1 = null;
  8. private ArrayList<Book> mData2 = null;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13. mContext = MainActivity.this;
  14. init();
  15. }
  16. private void init() {
  17. list_book = (ListView) findViewById(R.id.list_book);
  18. list_app = (ListView) findViewById(R.id.list_app);
  19. //数据初始化
  20. mData1 = new ArrayList<App>();
  21. mData1.add(new App(R.mipmap.iv_icon_baidu,"百度"));
  22. mData1.add(new App(R.mipmap.iv_icon_douban,"豆瓣"));
  23. mData1.add(new App(R.mipmap.iv_icon_zhifubao,"支付宝"));
  24. mData2 = new ArrayList<Book>();
  25. mData2.add(new Book("《第一行代码Android》","郭霖"));
  26. mData2.add(new Book("《Android群英传》","徐宜生"));
  27. mData2.add(new Book("《Android开发艺术探索》","任玉刚"));
  28. //Adapter初始化
  29. myAdapter1 = new MyAdapter<App>(mData1,R.layout.item_one) {
  30. @Override
  31. public void bindView(ViewHolder holder, App obj) {
  32. holder.setImageResource(R.id.img_icon,obj.getaIcon());
  33. holder.setText(R.id.txt_aname,obj.getaName());
  34. }
  35. };
  36. myAdapter2 = new MyAdapter<Book>(mData2,R.layout.item_two) {
  37. @Override
  38. public void bindView(ViewHolder holder, Book obj) {
  39. holder.setText(R.id.txt_bname,obj.getbName());
  40. holder.setText(R.id.txt_bauthor,obj.getbAuthor());
  41. }
  42. };
  43. //ListView设置下Adapter:
  44. list_book.setAdapter(myAdapter2);
  45. list_app.setAdapter(myAdapter1);
  46. }
  47. }

我们写的可复用的BaseAdapter的使用就如上面所述~


3.代码示例下载:

ListViewDemo4.zip

贴下最后写好的MyAdapter类吧,可根据自己的需求进行扩展:

MyAdapter.java

  1. /**
  2. * Created by Jay on 2015/9/22 0022.
  3. */
  4. public abstract class MyAdapter<T> extends BaseAdapter {
  5. private ArrayList<T> mData;
  6. private int mLayoutRes; //布局id
  7. public MyAdapter() {
  8. }
  9. public MyAdapter(ArrayList<T> mData, int mLayoutRes) {
  10. this.mData = mData;
  11. this.mLayoutRes = mLayoutRes;
  12. }
  13. @Override
  14. public int getCount() {
  15. return mData != null ? mData.size() : 0;
  16. }
  17. @Override
  18. public T getItem(int position) {
  19. return mData.get(position);
  20. }
  21. @Override
  22. public long getItemId(int position) {
  23. return position;
  24. }
  25. @Override
  26. public View getView(int position, View convertView, ViewGroup parent) {
  27. ViewHolder holder = ViewHolder.bind(parent.getContext(), convertView, parent, mLayoutRes
  28. , position);
  29. bindView(holder, getItem(position));
  30. return holder.getItemView();
  31. }
  32. public abstract void bindView(ViewHolder holder, T obj);
  33. //添加一个元素
  34. public void add(T data) {
  35. if (mData == null) {
  36. mData = new ArrayList<>();
  37. }
  38. mData.add(data);
  39. notifyDataSetChanged();
  40. }
  41. //往特定位置,添加一个元素
  42. public void add(int position, T data) {
  43. if (mData == null) {
  44. mData = new ArrayList<>();
  45. }
  46. mData.add(position, data);
  47. notifyDataSetChanged();
  48. }
  49. public void remove(T data) {
  50. if (mData != null) {
  51. mData.remove(data);
  52. }
  53. notifyDataSetChanged();
  54. }
  55. public void remove(int position) {
  56. if (mData != null) {
  57. mData.remove(position);
  58. }
  59. notifyDataSetChanged();
  60. }
  61. public void clear() {
  62. if (mData != null) {
  63. mData.clear();
  64. }
  65. notifyDataSetChanged();
  66. }
  67. public static class ViewHolder {
  68. private SparseArray<View> mViews; //存储ListView 的 item中的View
  69. private View item; //存放convertView
  70. private int position; //游标
  71. private Context context; //Context上下文
  72. //构造方法,完成相关初始化
  73. private ViewHolder(Context context, ViewGroup parent, int layoutRes) {
  74. mViews = new SparseArray<>();
  75. this.context = context;
  76. View convertView = LayoutInflater.from(context).inflate(layoutRes, parent, false);
  77. convertView.setTag(this);
  78. item = convertView;
  79. }
  80. //绑定ViewHolder与item
  81. public static ViewHolder bind(Context context, View convertView, ViewGroup parent,
  82. int layoutRes, int position) {
  83. ViewHolder holder;
  84. if (convertView == null) {
  85. holder = new ViewHolder(context, parent, layoutRes);
  86. } else {
  87. holder = (ViewHolder) convertView.getTag();
  88. holder.item = convertView;
  89. }
  90. holder.position = position;
  91. return holder;
  92. }
  93. @SuppressWarnings("unchecked")
  94. public <T extends View> T getView(int id) {
  95. T t = (T) mViews.get(id);
  96. if (t == null) {
  97. t = (T) item.findViewById(id);
  98. mViews.put(id, t);
  99. }
  100. return t;
  101. }
  102. /**
  103. * 获取当前条目
  104. */
  105. public View getItemView() {
  106. return item;
  107. }
  108. /**
  109. * 获取条目位置
  110. */
  111. public int getItemPosition() {
  112. return position;
  113. }
  114. /**
  115. * 设置文字
  116. */
  117. public ViewHolder setText(int id, CharSequence text) {
  118. View view = getView(id);
  119. if (view instanceof TextView) {
  120. ((TextView) view).setText(text);
  121. }
  122. return this;
  123. }
  124. /**
  125. * 设置图片
  126. */
  127. public ViewHolder setImageResource(int id, int drawableRes) {
  128. View view = getView(id);
  129. if (view instanceof ImageView) {
  130. ((ImageView) view).setImageResource(drawableRes);
  131. } else {
  132. view.setBackgroundResource(drawableRes);
  133. }
  134. return this;
  135. }
  136. /**
  137. * 设置点击监听
  138. */
  139. public ViewHolder setOnClickListener(int id, View.OnClickListener listener) {
  140. getView(id).setOnClickListener(listener);
  141. return this;
  142. }
  143. /**
  144. * 设置可见
  145. */
  146. public ViewHolder setVisibility(int id, int visible) {
  147. getView(id).setVisibility(visible);
  148. return this;
  149. }
  150. /**
  151. * 设置标签
  152. */
  153. public ViewHolder setTag(int id, Object obj) {
  154. getView(id).setTag(obj);
  155. return this;
  156. }
  157. //其他方法可自行扩展
  158. }
  159. }

本节小结:

本节给大家介绍了如何来实现一个可供复用的BaseAdapter,当然大家可以在这个的基础上根据
自己的需求进行修改,比如通过异步设置网络图片等~改代码是参考鸿洋大神的视频写的:
视频链接:Android-打造万能适配器
另外,实际编写中遇到一些问题,非常感谢Berial(B神)的耐心点拨~
ありがとうございます~

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注