RecyclerView学习(一)Android recyclerView 适配器使用方法

 
  

1、新建一个适配器类继承RecyclerView.Adapter泛型是内部类的ViewHolder,然后重写
onCreateViewHolder(返回一个新的ViewHolder对象)、onBindViewHolder(绑定ViewHolder)、getItemCount(此方法返回子项目的条数)方法。
2、新建内部类ViewHolder继承RecyclerView.ViewHolder重写构造方法,用于存储实例对象,加强性能。

    private List list;
    private Context context;

    public ListAdapter(List list, Context context) {
        this.list = list;
        this.context = context;
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView textView;
        public ViewHolder(View itemView) {
            super(itemView);
            imageView=itemView.findViewById(R.id.recycler_view_img);
            textView=itemView.findViewById(R.id.recycler_view_text);

        }
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.recyclerview_layout,null));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
         Menu menu=list.get(position);
         holder.imageView.setImageResource(menu.getIcon());
         holder.textView.setText(menu.getName());
    }

    @Override
    public int getItemCount() {
        return list!=null?list.size():0;
    }



}


你可能感兴趣的:(RecyclerView学习(一)Android recyclerView 适配器使用方法)