先写好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'
...
}