天天看點

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

點選檢視應用詳情