简单的实现ListView [复制链接]

2018-1-9 19:10
陈苗辉 阅读:750 评论:0 赞:0
Tag:??封装 ListView
现在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{

    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 viewHolder = (SparseArray) 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;
    }
}

我来说两句
您需要登录后才可以评论 登录 | 立即注册
facelist
所有评论(0)
领先的中文移动开发者社区
18620764416
7*24全天服务
意见反馈:1294855032@qq.com

扫一扫关注我们

Powered by Discuz! X3.2? 2001-2019 Comsenz Inc.( 粤ICP备15117877号 )