Recyclerview + Cardview Example: Alongside Button

Posted on

This instance operate on finally instance of “Gallery-like RecyclerView + CardView example” to demonstrate how to add together a push together with OnClickListener in RecyclerView + CardView. H5N1 ImageButton is add together over the photograph on each cell. Once user click on the ImageButton, the corresponding OnClickListener, to demonstrate the information of the corresponding photo.


Modify layout/layout_cardview.xml to add together a ImageButton.

<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:card_view="http://schemas.android.com/apk/res-auto"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_margin="10dp"     card_view:cardCornerRadius="5sp"     card_view:cardElevation="5sp">      <FrameLayout         android:layout_width="match_parent"         android:layout_height="wrap_content">          <ImageView             android:id="@+id/item_image"             android:layout_width="wrap_content"             android:layout_height="wrap_content" />         <ImageButton             android:id="@+id/buttonInfo"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:src="@android:drawable/ic_menu_info_details"             android:background="#00ffffff"/>      </FrameLayout> </android.support.v7.widget.CardView>  

Modify MyRecyclerViewAdapter.java:
– larn out the reference to the Button inwards the constructor of RecyclerView.ViewHolder.
– implement the OnClickListener inwards onBindViewHolder() of MyRecyclerViewAdapter.

package com.blogspot.android_er.androidgallery;  import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Toast;  import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List;  populace shape MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ItemHolder>{      soul List<Uri> itemsUri;     soul LayoutInflater layoutInflater;     soul Context context;     soul OnItemClickListener onItemClickListener;     MainActivity mainActivity;      populace MyRecyclerViewAdapter(Context context, MainActivity mainActivity){         this.context = context;         layoutInflater = LayoutInflater.from(context);         itemsUri = novel ArrayList<Uri>();          this.mainActivity = mainActivity;     }      @Override     populace MyRecyclerViewAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {         CardView itemCardView = (CardView)layoutInflater.inflate(R.layout.layout_cardview, parent, false);         furnish novel ItemHolder(itemCardView, this);     }      @Override     populace void onBindViewHolder(MyRecyclerViewAdapter.ItemHolder holder, finally int position) {         finally Uri targetUri = itemsUri.get(position);         holder.setItemUri(targetUri.getPath());          if (targetUri != null){              endeavour {                 //! CAUTION !                 //I'm non certain is it properly to charge bitmap here!                 holder.setImageView(loadScaledBitmap(targetUri));                  holder.btnInfo.setOnClickListener(new View.OnClickListener() {                     @Override                     populace void onClick(View v) {                         Toast.makeText(context,                                 "btnInfo clicked:\n"                                 + "position:" + seat + "\n"                                 + targetUri.getLastPathSegment(),                                 Toast.LENGTH_LONG).show();                     }                 });              } grab (FileNotFoundException e) {                 e.printStackTrace();             }         }     }      /*     reference:     Load scaled bitmap            */     soul Bitmap loadScaledBitmap(Uri src) throws FileNotFoundException {          //display the file to move loadScaledBitmap(),         //such that you lot tin scope the sack know how much operate on it.         mainActivity.textInfo.append(src.getLastPathSegment() + "\n");          // required max width/height         finally int REQ_WIDTH = 150;         finally int REQ_HEIGHT = 150;          Bitmap bm = null;          // First decode alongside inJustDecodeBounds=true to depository fiscal establishment check dimensions         finally 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 alongside inSampleSize gear upwards         options.inJustDecodeBounds = false;         bm = BitmapFactory.decodeStream(                 context.getContentResolver().openInputStream(src), null, options);          furnish bm;     }      populace int calculateInSampleSize(BitmapFactory.Options options,                                      int reqWidth, int reqHeight) {         // Raw superlative together with width of picture         finally int superlative = options.outHeight;         finally int width = options.outWidth;         int inSampleSize = 1;          if (height > reqHeight || width > reqWidth) {              // Calculate ratios of superlative together with width to requested superlative together with             // width             finally int heightRatio = Math.round((float) superlative                     / (float) reqHeight);             finally int widthRatio = Math.round((float) width / (float) reqWidth);              // Choose the smallest ratio equally inSampleSize value, this volition             // guarantee             // a finally picture alongside both dimensions larger than or equal to the             // requested superlative together with width.             inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;         }          furnish inSampleSize;     }      @Override     populace int getItemCount() {         furnish itemsUri.size();     }      populace void setOnItemClickListener(OnItemClickListener listener){         onItemClickListener = listener;     }      populace OnItemClickListener getOnItemClickListener(){         furnish onItemClickListener;     }      populace interface OnItemClickListener{         populace void onItemClick(ItemHolder item, int position);     }      populace void add(int location, Uri iUri){         itemsUri.add(location, iUri);         notifyItemInserted(location);     }      populace void clearAll(){         int itemCount = itemsUri.size();          if(itemCount>0){             itemsUri.clear();             notifyItemRangeRemoved(0, itemCount);         }     }       populace static shape ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener{          soul MyRecyclerViewAdapter parent;         soul CardView cardView;         ImageView imageView;         String itemUri;          ImageButton btnInfo;          populace ItemHolder(CardView cardView, MyRecyclerViewAdapter parent) {             super(cardView);             itemView.setOnClickListener(this);             this.cardView = cardView;             this.parent = parent;             imageView = (ImageView) cardView.findViewById(R.id.item_image);             btnInfo = (ImageButton) cardView.findViewById(R.id.buttonInfo);         }          populace void setItemUri(String itemUri){             this.itemUri = itemUri;         }          populace String getItemUri(){             furnish itemUri;         }          populace void setImageView(Bitmap bitmap){             imageView.setImageBitmap(bitmap);         }          @Override         populace void onClick(View v) {             finally OnItemClickListener listener = parent.getOnItemClickListener();             if(listener != null){                 listener.onItemClick(this, getLayoutPosition());                 //or purpose                 //listener.onItemClick(this, getAdapterPosition());             }         }     } }  

More instance of RecyclerView + CardView.