Android控件recycleview如何实现简化list布局及瀑布流布局
recycleview的优点
在动画,刷新需求上recycleview较之listview更完善和易扩展(这也是谷歌推之所强调的),其他方面两者皆可,list实现相对较简单, 自实际需求中,recycleview能更好的应对流式布局和横向滚动的view。
实现过程
引用依赖
// add to build.gradle
implement 'com.android.support:recyclerview-v7:23.4.0';
适配器
适配器adapter(继承recycleview.adapter),此处的泛型H需要实现一个内部类viewholder,实现onclick的接口,看注释。
// 父类和接口
public class MyRecycleradapter extends RecyclerView.Adapter<MyRecycleradapter.MyViewHolder> implements View.OnClickListener {
//itemlist数据
private List<News> mList;
private Context context;
private OnClickListener onClickListener;
//constrant方法
public OnClickListener getOnClickListener() {
return onClickListener;
}
public void setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
//构造是传入上下文和list数据
public MyRecycleradapter(@NonNull Context context, List<News> list) {
this.context=context;
this.mList=list;
}
@Override
public void onClick(View v) {
}
//重写viewholder
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
MyViewHolder myViewHolder;
View inflate = LayoutInflater.from(context).inflate(R.layout.list_item_post, viewGroup, false);
myViewHolder = new MyViewHolder(inflate);
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int i) {
//绑定视图和数据显示
News temp=mList.get(i);
Glide.with(context)
.load(temp.getMainpic())
.placeholder(R.drawable.loading)
.into(holder.vhimg);
holder.title.setText(temp.getTitle());
holder.hots.setText(Integer.toString(temp.getHots()));
holder.updatetimes.setText(temp.getUpdatedAt());
//设置监听事件
holder.itemView.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (onClickListener!=null){
onClickListener.onClick(holder.itemView,holder.getLayoutPosition());
}
}
});
}
@Override
public int getItemCount() {
return mList.size();
}
//内部类viewholder
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView vhimg;
TextView title;
TextView hots;
TextView updatetimes;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
vhimg=itemView.findViewById(R.id.vhimg);
title=itemView.findViewById(R.id.title);
hots=itemView.findViewById(R.id.hots);
updatetimes=itemView.findViewById(R.id.updatetimes);
}
}
//实现监听接口
public interface OnClickListener{
void onClick(View itemView,int position);
void onLongClick(View itemView,int position);
}
}
``
## Activity中绑定
```javascript
// 初始化视图
public void initRecycleView() {
myPicrecycleadapter=new MyPicrecycleadapter(mPiclist,context);
//layoutmanger管理视图,2数字代表行两个元素
RecyclerView.LayoutManager manager=new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL);
mypiclistview.setLayoutManager(manager);
mypiclistview.setAdapter(myPicrecycleadapter);
mypiclistview.setHasFixedSize(true);
//添加分割线
mypiclistview.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
}
小白总结,如有谬误,望请斧正