先上效果:
1.在MainActivity中找到recyclerview的组件
recyclerView1 = findViewById(R.id.recyclerView1);
2.设置为线性布局(这里在linearlayout,gridlayout,StaggeredGridLayout中选一种)
recyclerView1.setLayoutManager(new LinearLayoutManager(this));
3.初始化数据
initData();
这个方法的具体内容是:
private void initData() {
for(int i=0;i< DataUtil.names.length;i++){
StaffModel staffModel = new StaffModel(DataUtil.avatars[i],DataUtil.names[i],DataUtil.positions[i]);
staffList.add(staffModel);
}
}
4.初始化适配器
StaffAdapter adapter = new StaffAdapter(this,staffList);
5.设置适配器
recyclerView1.setAdapter(adapter);
适配器的设置单独写在了一个StaffAdapter页面,具体看下面代码:
public class StaffAdapter extends RecyclerView.Adapter<StaffAdapter.ViewHolder>{
Context context;
List<StaffModel> staffList;
public StaffAdapter(Context context,List<StaffModel> staffList){
this.context = context;
this.staffList = staffList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.staff_item