万能ViewHolder

最近发现一个比较好的代码,就是我们常用的ViewHolder,代码如下

public class ViewHolder {
    @SuppressWarnings("unchecked")
    public static <T extends View> T get(View view,int id){
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if(null == viewHolder){
            viewHolder = new SparseArray<View>();
            view.setTag(viewHolder);
        }

        View childView = viewHolder.get(id);
        if(null == childView){
            childView = view.findViewById(id);
            viewHolder.put(id,childView);
        }
        return (T)childView;
    }

}
相比之前的在每个Adapter中都写个ViewHolder这个方便了很多,直接调用工具类就好了,接下来上调用代码

public class MAdapter extends BaseAdapter {


    private final LayoutInflater inflater;

    public MAdapter(Context context) {
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

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

        ImageView iv = ViewHolder.get(view, R.id.iv);
        TextView tv = ViewHolder.get(view, R.id.tv);
        iv.setImageResource(R.drawable.image1);
        tv.setText("test");

        return view;
    }
}


如此一来是不是感觉方便了很多微笑


你可能感兴趣的:(viewholder,万能ViewHolder)