Android优化adapter及SparseArray介绍

在鸿洋大神的博文里介绍了Android 快速开发系列 打造万能的ListView GridView 适配器

在此,我直接把核心的部分截取出来详细记录一下:
这个是我在项目中使用的一个工具类:

public class ViewHolderUtil {

    /** * 获取容器中指定的元素 * * @param view * @param id * @return */
    @SuppressWarnings("unchecked")
    public static <T extends View> T get(View convertView, int id) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag(convertView.getId());//以id为键值的map
        if (viewHolder == null) {
            viewHolder = new SparseArray<View>();
            view.setTag(convertView.getId(), viewHolder);//设置子view的map
        }
        View childView = viewHolder.get(id);//从map中取子view
        if (childView == null) {
            childView = convertView.findViewById(id);
            viewHolder.put(id, childView);//将子view存放在map中
        }
        return (T) childView;
    }
}

在使用时,代码如下

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.search_item, null);
            }

            TextView title = ViewHolderUtil.get(convertView, R.id.title);//保证convertView不为空
            TextView authorTime = ViewHolderUtil.get(convertView, R.id.authorTime);
            TextView searchDetail = ViewHolderUtil.get(convertView, R.id.searchDetail);

            SearchResult result = dataList.get(position);
            if (result != null) {
                title.setText(result.title);
                authorTime.setText(result.authorTime);
                searchDetail.setText(result.searchDetail);
            }

            return convertView;
        }

因为convertView的tag以被设置为子view的map,所以在后面的使用中不可再次设置tag

为何map会使用SparseArray而不是HashMap呢?因为Android源码中就是这么干的,SparseArray比HashMap效率高多少
Android中的稀疏数组:SparseArray
结论是:当HashMap的key为整数时,则可以考虑使用SparseArray。

我写的CSDN博客客户端介绍:http://blog.csdn.net/brian512/article/details/43168141

点击查看应用详情

你可能感兴趣的:(android,SparseArra)