使用自定义Layout代替ViewHolder
2016-03-22 10:37
435 查看
ListView是非常常用android 控件,而对于ListView的优化,大家都想起了viewHolder模式了,很多人都写得滚瓜烂熟了。然而在Customizing Android ListView Rows by Subclassing中提到ViewHolder是一种愚昧的方式。为什么?以下是viewHolder模式的问题Create a layout for your row view.Create a “holder” class with fields to store child views of the row.For each new inflated row, create a holder instance and assign its fields to the results of calling
findViewById(int)for each child view.Set the instance of the holder as the top-level view’s tag with
setTag(Object).Reuse (and cast) the holder object for reused row views.那怎么办?作者在文章中提出了新的思路,通过自定义的Layout来代替ViewHolder关键代码:自定义Layout:MyLayoutpublic classMyLayout extendsRelativeLayout {
TextView tv_title; public MyLayout(Context context) { super(context); init(context); } private void init(Context context) { View view = LayoutInflater.from(context).inflate(R.layout.item_demo, this); tv_title = (TextView) view.findViewById(R.id.tv_title); } public void setData(String title) { tv_title.setText(title); } }
MyAdapter
public class MyAdapter extends BaseAdapter {private Context mContext;private List<String> mList;public MyAdapter(Context context, List<String> list) {mContext = context;mList = list;}@Overridepublic int getCount() {return mList == null ? 0 : mList.size();}@Overridepublic Object getItem(int position) {return null;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {MyLayout myLayout;if (convertView != null && convertView instanceof MyLayout) {myLayout = (MyLayout) convertView;} else {myLayout = new MyLayout(mContext);}myLayout.setData(mList.get(position));return myLayout;}}
done
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories