RecyclerView瀑布流加载图片实现

先写好RecyclerView的适配器.

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {

    private Context mContext;

    private LayoutInflater mInflater;

    private List<Bitmap> mBitmaps;

    public MyRecyclerAdapter(Context context,List<Bitmap> mBitmaps) {
        this.mBitmaps = mBitmaps;
        this.mContext = context;
        mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.list_item,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Bitmap bitmap = mBitmaps.get(position);
        holder.mImage.setImageBitmap(bitmap);
    }

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

    class MyViewHolder extends RecyclerView.ViewHolder {

        ImageView mImage;

        public MyViewHolder(View itemView) {
            super(itemView);
            mImage = (ImageView)itemView.findViewById(R.id.image_item);
        }
    }
}

RecyclerView item布局很简单,只是放一个imageView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/image_item"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

在MainActivity中,只需写好`写入图片数据,set好Adapter。
使用StaggeredGridLayoutManger实现瀑布流的效果。

RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
                recyclerView.setLayoutManager(layoutManager);
                adapter = new MyRecyclerAdapter(MainActivity.this,list);
                recyclerView.setAdapter(adapter);

使用StaggerGridLayoutManager时,需要导入包。

dependencies {
    ...
    compile 'com.android.support:appcompat-v7:21.0.3'
    ...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值