Android Recyclerview的瀑布流展示

//Activity的列表布局

//适配器里面的条目布局


    
        
            
            
        
    


 

//适配器

public class WaterfallAdpter extends RecyclerView.Adapter{

    private List list;
    private Context context;
    List heights = new ArrayList<>();

    public WaterfallAdpter(List list, Context context) {
        this.list = list;
        this.context = context;


    }

    @NonNull
    @Override
    public WaterfallAdpter.WaterfallHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new WaterfallAdpter.WaterfallHolder(LinearLayout.inflate(context,R.layout.waterfalllayout,null));
    }

    @Override
    public void onBindViewHolder(@NonNull WaterfallAdpter.WaterfallHolder holder, int position) {
        ViewGroup.LayoutParams layoutParams = holder.imageView.getLayoutParams();
        GongGeBean gongGeBean = list.get(position);
        //gongGeBean.imgHeight是在实体类里面定义的一个对象 在view里面赋值
        holder.imageView.getLayoutParams().height = gongGeBean.imgHeight;
        holder.textView.setText(list.get(position).getTitle());
        holder.imageView.setImageResource(list.get(position).getImg());


    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class WaterfallHolder extends RecyclerView.ViewHolder{
        private RelativeLayout relativeLayout;
        private ImageView imageView;
        private TextView textView;

        public WaterfallHolder(@NonNull View itemView) {
            super(itemView);
            relativeLayout = itemView.findViewById(R.id.re);
            imageView = itemView.findViewById(R.id.image_gongge);
            textView = itemView.findViewById(R.id.text_gongge);
        }
    }



}

//构造假数据

for (int i = 0;i<6;i++){
    GongGeBean gongGeBean = new GongGeBean();
    gongGeBean.setImg(R.mipmap.head);
    gongGeBean.setTitle("你好");
    gongGeBean.imgHeight = (i % 2)*100 + 400;//偶数和奇数的图片设置不同的高度,以到达错开的目的          list.add(gongGeBean);
}

//列表赋值

mBindingView.recyclerWaterfall.setLayoutManager( new StaggeredGridLayoutManager(2,
        StaggeredGridLayoutManager.VERTICAL));
mBindingView.recyclerWaterfall.setAdapter(new WaterfallAdpter(list,getActivity()));

//自己定义的假数据 可以根据需求定义多个对象

public class GongGeBean {
    public int imgHeight;
    private String title;
    private int img;

    public GongGeBean() {
    }

    public GongGeBean(String title, int img) {

        this.title = title;
        this.img = img;
    }

    public int getImgHeight() {
        return imgHeight;
    }

    public void setImgHeight(int imgHeight) {
        this.imgHeight = imgHeight;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getImg() {
        return img;
    }

    public void setImg(int img) {
        this.img = img;
    }

你可能感兴趣的:(Android Recyclerview的瀑布流展示)