1. 程式人生 > >RecyclerView瀑布流載入圖片實現

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'
    ...
}