ViewHolder模式超简洁写法

手机APP开发 2016-11-04

public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null)
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false);
        TextView name = ViewHolder.get(convertView, R.id.tv_name);
        name.setText("");
        return convertView;
}

class ViewHolder {
    // I added a generic return type to reduce the casting noise in client code
    @SuppressWarnings("unchecked")
    public static <T extends View> T get(View view, int id) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if (viewHolder == null) {
            viewHolder = new SparseArray<View>();
            view.setTag(viewHolder);
        }
        View childView = viewHolder.get(id);
        if (childView == null) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }
        return (T) childView;
    }
}

值得注意的是SparseArray这个知识点,优化过的存储integer和object键值对的hashmap

相关推荐