首先是activity_Main.xml
注意,少了下面那行活动页面会空白
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
1.然后需要创建一个java对象
public class NewsBean implements Serializable {
// private String title;
private String content;
private int img;
// private int
public NewsBean(String content, int img) {
this.content = content;
this.img = img;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
}
2.创建一个MyAdater适配器
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {
public List<NewsBean> mNewsBean=new ArrayList<>();
public MyAdapter(List<NewsBean> mNewsBean) {
this.mNewsBean = mNewsBean;
}
@NonNull
@Override
/*
* 创建并返回一个ViewHolder
* */
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.item,null);
return new MyHolder(view);
}
/*
* 数据绑定
* */
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
NewsBean newsBean = mNewsBean.get(position);
holder.tv.setText(newsBean.getContent());
holder.imageView.setImageResource(newsBean.getImg());
// holder.itemView.setId();
}
@Override
public int getItemCount() {
return mNewsBean.size();
}
/*
* 定义MyHolder并绑定控件;
* */
static class MyHolder extends RecyclerView.ViewHolder{
TextView tv;
ImageView imageView;
public MyHolder(@NonNull View itemView) {
super(itemView);
tv=itemView.findViewById(R.id.textView);
imageView=itemView.findViewById(R.id.imageView);
}
}
}
4.MainActivity的代码
public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private MyAdapter myAdapter; private List<NewsBean> newsBeanList=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView=findViewById(R.id.recyclerView); newsBeanList.add(new NewsBean("这是什么图片",R.drawable.thumb01)); newsBeanList.add(new NewsBean("这是什么图片",R.drawable.thumb02)); newsBeanList.add(new NewsBean("这是什么图片",R.drawable.thumb03)); newsBeanList.add(new NewsBean("这是什么图片",R.drawable.thumb01)); // newsBeanList.add(new NewsBean("zheshenme",R.drawable.thumb02)); myAdapter=new MyAdapter(newsBeanList); recyclerView.setAdapter(myAdapter); } }