Android RecyclerView及适配器简单使用

1.如果还没添加依赖包,则添加依赖包

implementation 'com.android.support:recyclerview-v7:27.1.0'

2.新建一个RecyclerViewAdapter
public class RecyclerviewAdapter extends RecyclerView.Adapter {

    private Context context;
    private List data;

    public RecyclerviewAdapter(Context context,List data){
        this.context = context;
        this.data = data;

    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_recyclerview,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        holder.name.setText(data.get(position));

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("这里是点击每一行item的响应事件",""+position+item);
            }
        });

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        private TextView name;

        public ViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);

        }
    }
}


3.在Activity中加载RecyclerView

RecyclerviewAdapter adapter = new RecyclerviewAdapter(this,data);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

recyclerView.setLayoutManager(new LinearLayoutManager(this));
要给recyclerview设置布局管理器,否则不显示内容

你可能感兴趣的