现在RecyclerView已经代替LisvView,但是个别时候我们还会用到,使用封装好的简单暴力!
listView的优化我就不说了,谷歌百度一大片,把封装好的ViewHolder和Adapter直接展示给大家
1.把Adapter封装成抽象类:
/** * 封装的adapter(泛型) 抽象类 * Created by cmh on 2018/1/8. */public abstract class DAdapter<T> extends BaseAdapter { private Context context; private List<T> datalist; public DAdapter(Context context) { this.context = context; } //可以调用context public Context getContext() { return context; } public List<T> getDatalist() { return datalist; } public void setDatalist(List<T> datalist) { this.datalist = datalist; } @Override public int getCount() { if (datalist!=null){ return datalist.size(); } return 0; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } //抽象方法 @Override public abstract View getView(int position, View convertView, ViewGroup parent); }
2.Adapter extends DAdapter<实体类>
/** * 继承封装好的adapter * Created by cmh on 2018/1/8. */public class FMyAdapter extends DAdapter<Hore>{ public FMyAdapter(Context context) { super(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (null==convertView){ convertView = LayoutInflater.from(getContext()).inflate(R.layout.plist_item,null); } //viewHolder获取控件绑定convertView ImageView imageView = DViewHolder.get(convertView,R.id.img); TextView textView = DViewHolder.get(convertView,R.id.tv); Hore hore = getDatalist().get(position); //展示数据 imageView.setImageResource(hore.getResId()); textView.setText(hore.getName()); return convertView; } }
3.封装ViewHolder(直接使用)
/** * 封装的viewholder * Created by cmh on 2018/1/8. */public class DViewHolder { 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.setTag(viewHolder); } View childView = viewHolder.get(id); if (childView==null){ childView = view.findViewById(id); viewHolder.put(id,childView); } return (T) childView; } }
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦