implementation 'com.android.support:recyclerview-v7:27.+'
//将数据源设置给适配器 SubAdapter subAdapter = new SubAdapter(MainActivity.this, list); subAdapter.setOnItemClickLisentener(new SubAdapter.onItemClickLisentener() { @Override public void onItemClick(int position) { Toast.makeText(MainActivity.this, "第" + position + "个条目", Toast.LENGTH_SHORT).show(); } }); //设置线性管理器 // LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false); // GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 2, GridLayoutManager.VERTICAL, false); StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); //设置条目管理器 recycel_vie.setLayoutManager(staggeredGridLayoutManager); //设置适配器 recycel_vie.setAdapter(subAdapter);
适配器
package com.bwei.recyclerview_01; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bwei.recyclerview_01.bean.Bean; import java.util.List; /** * Created by Jack Lee on 2018/8/14. * name:Juck Lee */ class SubAdapter extends RecyclerView.Adapter<SubAdapter.SubHolder>{ private Context context; private List<Bean.DataBean> list; onItemClickLisentener onItemClickLisentener; public void setOnItemClickLisentener(onItemClickLisentener onItemClickLisentener) { this.onItemClickLisentener = onItemClickLisentener; } //声明借口对象 public interface onItemClickLisentener{ //声明条目点击方法 void onItemClick(int position); } public SubAdapter(Context context, List<Bean.DataBean> list) { this.context = context; this.list = list; } @NonNull @Override public SubHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // View view = View.inflate(context, R.layout.recycler_item, null); View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false); SubHolder subHolder = new SubHolder(view); ViewGroup.LayoutParams layoutParams = subHolder.itemView.getLayoutParams(); layoutParams.height = (int) (100+Math.random()*400); //设置给原有条目 subHolder.itemView.setLayoutParams(layoutParams); return subHolder; } @Override public void onBindViewHolder(@NonNull SubHolder holder, int position) { holder.text_view.setText(list.get(position).getTitle()); } @Override public int getItemCount() { return list.size(); } class SubHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView text_view; public SubHolder(View itemView) { super(itemView); text_view = itemView.findViewById(R.id.text_view); itemView.setOnClickListener(this); } @Override public void onClick(View v) { //获取当前位置 int position = getLayoutPosition(); onItemClickLisentener.onItemClick(position); } } }