Gallery-Like Recyclerview + Cardview Example

Posted on

Influenza A virus subtype H5N1 long long fourth dimension ago, nosotros convey Implement Android Gallery widget“. But it deprecated and no longer supported.

So inwards long fourth dimension agone at 2012, I convey approximately other event to “Implement Gallery-like HorizontalScrollView“.

Now, with RecyclerView together with CardView, it’s approximately other event to implement Gallery-like RecyclerView + CardView. It display files in ExternalStorageDirectoryPath + “/test/” folder.
(If you lot desire to charge from other user selectable folder, cite “Intent.ACTION_OPEN_DOCUMENT (from API marking 19) to charge images inwards RecyclerView + CardView“.)

To role RecyclerView + CardView, nosotros convey to “Add Support Libraries of RecyclerView, CardView to Android Studio Project“.

Create our RecyclerView.Adapter,

package com.blogspot.android_er.androidgallery;  import android.content.Context; import; import; import; import; import; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView;  import; import java.util.ArrayList; import java.util.List;  world shape MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ItemHolder>{      someone List<Uri> itemsUri;     someone LayoutInflater layoutInflater;     someone Context context;     someone OnItemClickListener onItemClickListener;     MainActivity mainActivity;      world MyRecyclerViewAdapter(Context context, MainActivity mainActivity){         this.context = context;         layoutInflater = LayoutInflater.from(context);         itemsUri = novel ArrayList<Uri>();          this.mainActivity = mainActivity;     }      @Override     world MyRecyclerViewAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {         CardView itemCardView = (CardView)layoutInflater.inflate(R.layout.layout_cardview, parent, false);         provide novel ItemHolder(itemCardView, this);     }      @Override     world void onBindViewHolder(MyRecyclerViewAdapter.ItemHolder holder, int position) {         Uri targetUri = itemsUri.get(position);         holder.setItemUri(targetUri.getPath());          if (targetUri != null){              seek {                 //! CAUTION !                 //I'm non certain is it properly to charge bitmap here!                 holder.setImageView(loadScaledBitmap(targetUri));             } pick out grip of (FileNotFoundException e) {                 e.printStackTrace();             }         }     }      /*     reference:     Load scaled bitmap            */     someone Bitmap loadScaledBitmap(Uri src) throws FileNotFoundException {          //display the file to hold out loadScaledBitmap(),         //such that you lot tin post away know how much run on it.         mainActivity.textInfo.append(src.getLastPathSegment() + "\n");          // required max width/height         in conclusion int REQ_WIDTH = 150;         in conclusion int REQ_HEIGHT = 150;          Bitmap bm = null;          // First decode amongst inJustDecodeBounds=true to banking concern check dimensions         in conclusion BitmapFactory.Options options = novel BitmapFactory.Options();         options.inJustDecodeBounds = true;         BitmapFactory.decodeStream(context.getContentResolver().openInputStream(src),                 null, options);          // Calculate inSampleSize         options.inSampleSize = calculateInSampleSize(options, REQ_WIDTH,                 REQ_HEIGHT);          // Decode bitmap amongst inSampleSize laid         options.inJustDecodeBounds = false;         bm = BitmapFactory.decodeStream(                 context.getContentResolver().openInputStream(src), null, options);          provide bm;     }      world int calculateInSampleSize(BitmapFactory.Options options,                                      int reqWidth, int reqHeight) {         // Raw peak together with width of icon         in conclusion int peak = options.outHeight;         in conclusion int width = options.outWidth;         int inSampleSize = 1;          if (height > reqHeight || width > reqWidth) {              // Calculate ratios of peak together with width to requested peak together with             // width             in conclusion int heightRatio = Math.round((float) peak                     / (float) reqHeight);             in conclusion int widthRatio = Math.round((float) width / (float) reqWidth);              // Choose the smallest ratio equally inSampleSize value, this volition             // guarantee             // a in conclusion icon amongst both dimensions larger than or equal to the             // requested peak together with width.             inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;         }          provide inSampleSize;     }      @Override     world int getItemCount() {         provide itemsUri.size();     }      world void setOnItemClickListener(OnItemClickListener listener){         onItemClickListener = listener;     }      world OnItemClickListener getOnItemClickListener(){         provide onItemClickListener;     }      world interface OnItemClickListener{         world void onItemClick(ItemHolder item, int position);     }      world void add(int location, Uri iUri){         itemsUri.add(location, iUri);         notifyItemInserted(location);     }      world void clearAll(){         int itemCount = itemsUri.size();          if(itemCount>0){             itemsUri.clear();             notifyItemRangeRemoved(0, itemCount);         }     }       world static shape ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener{          someone MyRecyclerViewAdapter parent;         someone CardView cardView;         ImageView imageView;         String itemUri;          world ItemHolder(CardView cardView, MyRecyclerViewAdapter parent) {             super(cardView);             itemView.setOnClickListener(this);             this.cardView = cardView;             this.parent = parent;             imageView = (ImageView) cardView.findViewById(;         }          world void setItemUri(String itemUri){             this.itemUri = itemUri;         }          world String getItemUri(){             provide itemUri;         }          world void setImageView(Bitmap bitmap){             imageView.setImageBitmap(bitmap);         }          @Override         world void onClick(View v) {             in conclusion OnItemClickListener listener = parent.getOnItemClickListener();             if(listener != null){                 listener.onItemClick(this, getLayoutPosition());                 //or role                 //listener.onItemClick(this, getAdapterPosition());             }         }     } }  


<?xml version="1.0" encoding="utf-8"?> <     xmlns:android=""     xmlns:card_view=""     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_margin="10dp"     card_view:cardCornerRadius="5sp"     card_view:cardElevation="5sp">      <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:orientation="vertical">          <ImageView             android:id="@+id/item_image"             android:layout_width="wrap_content"             android:layout_height="wrap_content" />      </LinearLayout> </>

package com.blogspot.android_er.androidgallery;  import; import android.os.Bundle; import android.os.Environment; import; import; import; import android.text.method.ScrollingMovementMethod; import android.widget.TextView; import android.widget.Toast;  import;  world shape MainActivity extends AppCompatActivity         implements MyRecyclerViewAdapter.OnItemClickListener{      someone RecyclerView myRecyclerView;     someone MyRecyclerViewAdapter myRecyclerViewAdapter;     someone LinearLayoutManager linearLayoutManager;      TextView textInfo;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          textInfo = (TextView)findViewById(;         textInfo.setMovementMethod(new ScrollingMovementMethod());          myRecyclerView = (RecyclerView)findViewById(;         linearLayoutManager =                 novel LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);         myRecyclerViewAdapter = novel MyRecyclerViewAdapter(this, this);         myRecyclerViewAdapter.setOnItemClickListener(this);         myRecyclerView.setAdapter(myRecyclerViewAdapter);         myRecyclerView.setLayoutManager(linearLayoutManager);          prepareGallery();     }      someone void prepareGallery(){         String ExternalStorageDirectoryPath = Environment                 .getExternalStorageDirectory()                 .getAbsolutePath();         String targetPath = ExternalStorageDirectoryPath + "/test/";          Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();         File targetDirector = novel File(targetPath);          File[] files = targetDirector.listFiles();         for (File file : files){             Uri uri = Uri.fromFile(file);             myRecyclerViewAdapter.add(                     myRecyclerViewAdapter.getItemCount(),                     uri);         }     }      @Override     world void onItemClick(MyRecyclerViewAdapter.ItemHolder item, int position) {          String stringitemUri = item.getItemUri();         Toast.makeText(MainActivity.this, stringitemUri, Toast.LENGTH_SHORT).show();     } }  


<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=""     xmlns:tools=""     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     android:padding="16dp"     tools:context=".MainActivity">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"         android:autoLink="web"         android:text=""         android:textStyle="bold" />      <         android:id="@+id/myrecyclerview"         android:layout_width="match_parent"         android:layout_height="170dp" />      <TextView         android:id="@+id/info"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:typeface="monospace"         android:gravity="bottom"/>  </LinearLayout>  

To read diles in ExternalStorage, uses-permission of “android.permission.READ_EXTERNAL_STORAGE” is needed inwards AndroidManifest.xml.

If you lot desire to charge from other user selectable folder Gallery-like RecyclerView + CardView exampleDownload the files (Android Studio Format) .

– RecyclerView + CardView example: amongst Button

More event of RecyclerView + CardView.