<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rcv"
/>
创建一个布局文件为Recylerview设置显示的格式
创建Adapter
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {
private List<ItemBean> itemBeans;
private LayoutInflater layoutInflater;
private Context context;
public MyRecyclerAdapter(Context context , List<ItemBean> itemBeans){
this.context = context;
this.itemBeans = itemBeans;
layoutInflater = LayoutInflater.from(context);
}
//创建ViewHolder
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//实例化显示格式的布局文件
View view = layoutInflater.inflate(R.layout.list_item_layout, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
ItemBean itemBean = itemBeans.get(position);
holder.textViewTitle.setText(itemBean.getTitle());
holder.textViewBody.setText(itemBean.getContent());
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
@Override
public int getItemCount() {
return itemBeans.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewBody;
ImageView imageView;
//点击事件 (头id)
RelativeLayout relativeLayout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.tv_title);
textViewBody = itemView.findViewById(R.id.tv_body);
imageView = itemView.findViewById(R.id.iv_img);
//点击事件
relativeLayout = itemView.findViewById(R.id.rl_item_container);
}
}
}
Activity
private RecyclerView recyclerView;
private List<ItemBean> itemBeans;
private MyRecyclerAdapter myRecyclerAdapter;
private void initView() {
recyclerView = findViewById(R.id.rcv);
}
private void initData() {
//创建数组
itemBeans = new ArrayList<>();
//准备数据
ItemBean itemBean1 = new ItemBean();
itemBean1.setTitle("我是i但撒谎嗲是丢啊是大i撒谎的奥萨蒂还大还大阿萨");
itemBean1.setContent("ldksudoijclxjd4fef51er35f1");
//数据添加到数组中
itemBeans.add(itemBean1);
}
private void initAdapter() {
myRecyclerAdapter = new MyRecyclerAdapter(this,itemBeans);
recyclerView.setAdapter(myRecyclerAdapter);
//设置显示模式 有三种
//线性布局 (第一个参数上下文、第二个显示的方向、第三个是否反转(从下往上))
//LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
//网格布局 (第一个参数上下文、第二个显示的格子几个、第三个是否反转(从下往上))
//GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
//破布流布局 (第一个每行几个、第二个方向、)
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
}
标签:基本,RecyclearView,itemView,private,id,使用,new,itemBeans,public
From: https://www.cnblogs.com/loulan/p/16974847.html