一、Listview
二、Gridview
三、RecyclerView
- 添加依赖
implementation 'com.android.support:recyclerview-v7:28.0.0'
- 布局中添加 RecyclerView
<android.support.v7.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" />
- 适配器
public class ArticleListAdatper extends RecyclerView.Adapter<ArticleListAdatper.MyViewHolder> {
private List<ArticleListBean.DataBean.ListBean> usefulThingBeanLists;
private Context context;
public ArticleListAdatper(List<ArticleListBean.DataBean.ListBean> usefulThingBeanLists, Context usefulThingListActivity) {
this.usefulThingBeanLists = usefulThingBeanLists;
this.context = usefulThingListActivity;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_useful_thing, viewGroup, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int i) {
final ArticleListBean.DataBean.ListBean listBean = usefulThingBeanLists.get(i);
Picasso.with(context)
.load(listBean.getCoverUrl())
.into(viewHolder.iv_article_picture);
}
@Override
public int getItemCount() {
return usefulThingBeanLists.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder {
//布局中的id
ImageView iv_article_picture;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
iv_article_picture = itemView.findViewById(R.id.iv_article_picture);
}
}
}
适配器解释:
①首先自定义一个适配器ArticleListAdatper 集成自RecyclerView,Adapter,并将泛型指定为ArticleListAdatper.MyViewHolder;
②自定义MyViewHolder继承自 RecyclerView.ViewHolder,里边实现获取条目布局id的功能;
③重写方法 RecyclerView.ViewHolder,通过布局加载器加载条目布局,创建MyHolderVIew对象并返回;
④重写方法onBindViewHolder,用来赋值、加载图片、点击事件;
⑤重写方法getItemCount;
⑥该适配器的构方法,带有数据和上下文。
- 使用recyclerview
RecyclerView rv = (RecyclerView )findviewById(R.id.rv);
LinerLayoutManager linearLayoutManager= new LInerLayoutManager(this);
//设置列表方向,默认为纵向滚动
linearLayoutManager.setOrientation(LInerLayoutManager.HORIZONTAL);
ArticleListAdatper adatper = new ArticleListAdatper(List, mContext);
rv.setAdapter(articleListAdatper);
除了LinerLayoutManager之外,还提供了GridLayoutManager(网格布局)和StaggerGridLayoutManager(瀑布流布局)。
网友评论