How can I pass the data from view to another activity? - android

I have used CardView inside a RecyclerView in horizontal manner. Now what I want to do is, when user click on a card then the data which I have putted into the intent with the help of putExtra function should be passed to the next activity.
Here is the code
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private List<Section> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, List<Section> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
Section singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
holder.tvAuthor.setText(singleItem.getAuthorname());
holder.tvPremium.setText(singleItem.getPremium());
Glide.with(mContext)
.load(singleItem.getImage()
.into(holder.itemImage);
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tvTitle, tvAuthor, tvPremium;
protected ImageView itemImage;
public SingleItemRowHolder(final View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tvTitle1);
this.tvAuthor = (TextView) view.findViewById(R.id.tvTitle2);
this.tvPremium = (TextView) view.findViewById(R.id.txtSubText1);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), BooksDescription.class);
intent.putExtra("id", NavigationDrawer.ID.get());
mContext.startActivity(intent);
}
});
}
}
}
Here in the line intent.putExtra("id", NavigationDrawer.ID); NavigationDrawe.ID having 20 integer data. Now which function should I use to get the data of only those card which is clicked.

Related

Android: Pass text from Textview when clicking an Image button inside recycler view

So I have a recycler view with 2 texts and 1 image button. I want to click the image button and then open a new activity and transfering the text from the textViewADV1 to the next activity
My items .xml in my recyclerview consist of the following
<ImageButton
android:id="#+id/imageButton1"
android:clickable="true"
android:onClick="openActivity2"/>
<TextView
android:id="#+id/textViewADV1"
android:text="Line 1"/>
<TextView
android:id="#+id/textViewADV2"
android:text="Line 2"/>
My openActivity2() from Main Activity
public void openActivity2(View view)
{
Intent intentLoadNewActivity = new Intent(AdvancedResults.this,OpenSelectedAdvanced.class);
startActivity(intentLoadNewActivity);
}
I tried doing textViewADV1.getText().toString() but it only reads the text from the first item in the recycler view
My recycler adapter
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
public String mImage;
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImagebtn;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView) {
super(itemView);
mImagebtn = itemView.findViewById(R.id.imageButtonADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList) {
mAdvancedList = advancedList;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
Picasso.get().load(mImage).into(holder.mImagebtn);
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
}
First of all pass a context to your adapter when you initialize it:
//in the main activity that you initialize the adapter in
AdvancedAdapter adapter = new AdvancedAdapter(your_list , MainActivity.this);
Now change the constructor of AdvancedAdapter to accept context
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
private Context context;
.............
//constructor
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList,Context context) {
mAdvancedList = advancedList;
this.context = context;
}
Now in onBindViewHolder in the AdvancedAdapter
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
Picasso.get().load(mImage).into(holder.mImagebtn);
//on click image button
hodler.mImagebtn.setOnclickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(context , OpenSelectedAdvanced.class);
intent.putExtra("data" , currentItem.getText1());
context.startActivity(intent);
}
});
}
To get the data from OpenSelectedAdvanced activity:
//in oncreate method:
Intent intent = getIntent();
//this is your text view text that came from the clicked image button
String transferedText = intent.getStringExtra("data");
If you have declared your onBindViewHolder() in your adapter class so why are you starting activity from MainActivity. You should add setOnclicklistenr() in onBindViewHolder() to achieve the desired result that you want that is in following way :
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
//one more thing you have to create Context field so that you can
//you can start the activity from any context (From Any activity)
private Context mContext;
public String mImage;
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImagebtn;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView) {
super(itemView);
mImagebtn = itemView.findViewById(R.id.imageButtonADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList, Context mContext) {
mAdvancedList = advancedList;
this.mContext = mContext;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
holder.mImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here You start your activity
Intent intent = new Intent(mContext, Activity2.class);
//you can putExtras here
mContext.startActivity(intent);
});
Picasso.get().load(mImage).into(holder.mImagebtn);
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
}
Now initialize this adapter in your activity where you implemented recyclerView And Send that arraylist into the parameters of that constructor of your adapter :) if did not understand yet you can try the tutorial on the link given below : https://www.youtube.com/watch?v=bIppSKk9afI

How to getting the current value when i clicked my recycler view

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDatasetname;
private Integer[] mexp;
Context context;
public ToggleButton select;
Integer selectedcountint=0;
private Bitmap[] mpro;
private String[] mloc;
private String[] mobj;
private String[] mselected;
public ArrayList<String> nselected = new ArrayList<>();
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public TextView texp;
public Button pdf;
public ToggleButton select;
public ImageView pro;
public TextView loc;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
texp = (TextView) v.findViewById(R.id.setexp);
pdf = (Button) v.findViewById(R.id.moreinfo);
select = (ToggleButton) v.findViewById(R.id.select);
pro = (ImageView) v.findViewById(R.id.setpropic);
loc = (TextView) v.findViewById(R.id.setlocation);
}
}
public MyAdapter(String[] myDataset,Integer[] exp,Bitmap[] pro,String[] loc,String[] obj){
mDatasetname = myDataset;
mexp=exp;
mpro=pro;
mloc=loc;
mobj=obj;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
context=parent.getContext();
View vs = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(vs);
return vh;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position){
holder.mTextView.setText(mDatasetname[position]);
holder.texp.setText(String.valueOf(mexp[position])+" yrs");
holder.pro.setImageBitmap(mpro[position]);
holder.loc.setText(mloc[position]);
holder.select.setText("rejected");
holder.pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent = new Intent(context, PdfViewer.class);
intent.putExtra("obj",mobj[position]);
context.startActivity(intent);
}
});
holder.select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked==true) {
holder.select.setChecked(true);
holder.select.setText("selected");
nselected.remove(mobj[position]+",rejected");
nselected.add(mobj[position]+",selected");
Log.d("dei", String.valueOf(nselected));
selectedcountint=selectedcountint+1;
Intent intent = new Intent("custom-message");
// intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)nselected);
intent.putExtra("BUNDLE",args);
intent.putExtra("totalval",selectedcountint);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} else {
holder.select.setChecked(false);
holder.select.setText("rejected");
nselected.remove(mobj[position]+",selected");
nselected.add(mobj[position]+",rejected");
Log.d("dei", String.valueOf(nselected));
selectedcountint=selectedcountint-1;
Intent intent = new Intent("custom-message");
// intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)nselected);
intent.putExtra("BUNDLE",args);
intent.putExtra("totalval",selectedcountint);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
});
}
#Override
public int getItemCount() { return mDatasetname.length; }
}
I have a recycler view in my app. I am having a problem. There is an item so that when I click on the item a the funtion in the click b is executed. It would be very great when you clean up the below code for me because I am new to programming, so that I won't be able to solve the problem.
if(getAdapterPosition() != RecyclerView.NO_POSITION) {
...
mobj[getAdapterPosition()]
...
}
It's better if you set your data and listeners in the ViewHolder. You should create a method in your ViewHolder class and pass there item from your list as a parameter. In this method you copy all your code for setting text and listeners. Then in onBindViewHolder you call this method.
First create a class that will be our Adapter item (you should change the names of the fields because I don't know what should they represent, this is just an example):
class AdapterItem {
private String firstString;
private Integer integerValue;
private Bitmap bitmap;
private String secondString;
private String thirdString;
// create also getters, setters for fields
}
Your adapters constructor will look something like this:
public MyAdapter(ArrayList<AdapterItem> data){
this.data = data;
}
And the onBindViewHolder method:
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position){
holder.bind(data[position]);
}
In the ViewHolder class:
void bind(AdapterItem item) {
mTextView.setText(item.getFirstString());
pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, PdfViewer.class);
intent.putExtra("obj", item.getThirdString());
v.getContext().startActivity(intent);
}
});
}
As correctly pointed out by #andrei The code to get the correct string from the obj[] array should be as shown:
public MyAdapter(Context context, String[] myDataset,Integer[] exp,Bitmap[] pro,String[] loc,String[] obj){
mContext = context; // make mContext as a variable like others
mDatasetname = myDataset;
mexp=exp;
mpro=pro;
mloc=loc;
mobj=obj;
}
holder.pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent = new Intent(context, PdfViewer.class);
intent.putExtra("obj",mobj[holder.getAdapterPosition()]);
mContext.startActivity(intent);
}
});
And similarly replace all occurrences of position with holder.getAdapterPosition() because holder.getAdapterPosition() will always give you the updated position for an item of recycler view in your code as if you update or delete items without using notifyDataSetChanged() method then the onBindViewHolder will not be called again hence the position will become inconsistent. For detailed information you can refer to this answer.
public class MyAdapter extends RecyclerView.Adapter {
private String[] mDatasetname;
private Integer[] mexp;
private Context context;
public ToggleButton select;
Integer selectedcountint=0;
private Bitmap[] mpro;
private String[] mloc;
private String[] mobj;
public Button pdf;Context m;private String[] mselected;
public ArrayList<String> nselected = new ArrayList<>();
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public TextView texp;
public Button pdf;
public ToggleButton select;
public ImageView pro;
public MainActivity activity;
public Context ipaset;
public TextView loc;
public View layout;
View forresumeview;
String forresume;
private RecyclerView.ViewHolder s;
public MyViewHolder(final View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
texp = (TextView) v.findViewById(R.id.setexp);
pdf = (Button) v.findViewById(R.id.moreinfo);
select = (ToggleButton) v.findViewById(R.id.select);
pro = (ImageView) v.findViewById(R.id.setpropic);
loc = (TextView) v.findViewById(R.id.setlocation);
forresumeview=v;
}
void bind(String name, Integer exp, String location, final Bitmap image, final String obj ){
mTextView.setText(name);
texp.setText(String.valueOf(exp) + " yrs");
pro.setImageBitmap(image);
loc.setText(location);
}
public void doonce(final String s){
pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vs) {
Intent intent = new Intent(forresumeview.getContext(), PdfViewer.class);
intent.putExtra("obj", s);
forresumeview.getContext().startActivity(intent);
// Log.d("sdasd", obj);
}
});
}
}
public MyAdapter(String[] myDataset,Integer[] exp,Bitmap[] pro,String[] loc,String[] obj){
mDatasetname = myDataset;
mexp=exp;
mpro=pro;
mloc=loc;
mobj=obj;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
context=parent.getContext();
View vs = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(vs);
return vh;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position){
holder.bind(mDatasetname[position],mexp[position],mloc[position],mpro[position],mobj[position]);
holder.doonce(mobj[position]);
}
#Override
public int getItemCount() { return mDatasetname.length; }
}
this is the answer ,,,, it works i tried it !!!! Happy coding ......

error onclicklistener on recyclerview

i have a recyclerview and i want to when click on it receive the position and one String and sent to other activity and run it
i dont know where this code has problem.
Mainactivity
#Override
public void onItemClick(int i) {
datamodel clickedItem = postlist.get(i);
Intent detailIntent = new Intent(MainActivity.this, Main2Activity.class);
detailIntent.putExtra(EXTRA_URL, clickedItem.getmTitle());
startActivity(detailIntent);
}
Adapter codes:
public class rrecyclerviewadapter extends RecyclerView.Adapter<rrecyclerviewadapter.myholder> {
private OnItemClickListener mListener;
private Context context;
private List<datamodel>mylist;
public interface OnItemClickListener {
void onItemClick(int i);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mListener = listener;
}
public rrecyclerviewadapter(Context context, List<datamodel>mylist){
this.context=context;
this.mylist=mylist;
}
#NonNull
#Override
public myholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(context).inflate(R.layout.each_item,viewGroup,false);
return new myholder(view);
}
#Override
public void onBindViewHolder(#NonNull myholder myholder, int i) {
datamodel datamodel=mylist.get(i);
myholder.eachitemtxt.setText(datamodel.getmTitle());
Picasso.with(context).load(datamodel.getMimageurl()).placeholder(R.drawable.pic3).error(R.drawable.pic4).into(myholder.eachitemimg);
}
#Override
public int getItemCount() {
return mylist.size();
}
public class myholder extends RecyclerView.ViewHolder {
private TextView eachitemtxt;
private ImageView eachitemimg;
public myholder(#NonNull final View itemView) {
super(itemView);
eachitemimg = (ImageView) itemView.findViewById(R.id.imageview_eachitem);
eachitemtxt = (TextView) itemView.findViewById(R.id.textview_eachitem);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "id:" + getAdapterPosition(),
Toast.LENGTH_SHORT).show();
int i=getAdapterPosition();
if (i != RecyclerView.NO_POSITION) {
mListener.onItemClick(i);
}}
});}}}
here there is full adapter code
on other activity i get intent.
in the adapter when testing Toast its completely works but on the mlistener and
setting id it does not work
found it.
just need to add
Adapter.setOnItemClickListener(Activitymain.this)
to your Mainactivity
i just changed your holder class in adapter try the below code
public class myholder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView eachitemtxt;
private ImageView eachitemimg;
public myholder(#NonNull final View itemView) {
super(itemView);
eachitemimg = (ImageView) itemView.findViewById(R.id.imageview_eachitem);
eachitemtxt = (TextView) itemView.findViewById(R.id.textview_eachitem);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int p = getAdapterPosition();
datamodel clickedItem = postlist.get(p);
Intent detailIntent = new Intent(context, Main2Activity.class);
detailIntent.putExtra(EXTRA_URL, clickedItem.getmTitle());
context.startActivity(detailIntent);
}
}

how to get a card position in RecyclerView.Adapter?

Please help me with a problem. The problem is that I need to get the card position to convey this position to another Activity. I need to transfer this position when I pressed the button on the card. How to get the card position?
RVAdapter.java
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
private final static String myLog = "myLog";
List<ItemsOfRow> items;
private Context context;
RVAdapter(List<ItemsOfRow> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
personViewHolder.imgGroupImage.setImageBitmap(items.get(i).getTitleImage());
personViewHolder.txtTitleGroup.setText(items.get(i).getTitleName());
personViewHolder.txtContentGroup.setText(items.get(i).getTitleContent());
personViewHolder.btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, items.get(????).getTitleContent());
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
});
personViewHolder.btnLearnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, QuoteActivity.class);
intent.putExtra("title",items.get(?????).getTitleName());
intent.putExtra("positionGroup", ?????? + "");
view.getContext().startActivity(intent);
}
});
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView txtTitleGroup;
TextView txtContentGroup;
ImageView imgGroupImage;
Button btnShare;
Button btnLearnMore;
PersonViewHolder(final View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
imgGroupImage = (ImageView) itemView.findViewById(R.id.img_group_image);
txtTitleGroup = (TextView) itemView.findViewById(R.id.txt_title_group);
txtContentGroup = (TextView) itemView.findViewById(R.id.txt_content_group);
btnShare = (Button) itemView.findViewById(R.id.btn_share_group);
btnLearnMore = (Button) itemView.findViewById(R.id.btn_learn_more);
}
}
}
You can use method getAdapterPosition() of your viewHolder
The second parameter int i of onBindViewHolder() is actually the position of the card that is going to be created. You can just pass i to your intent.
In your onBindViewHolder
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
/* rest of your code */
personViewHolder.btnLearnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, QuoteActivity.class);
intent.putExtra("title",items.get(i).getTitleName());
intent.putExtra("positionGroup", i);
view.getContext().startActivity(intent);
}
});
}
recyclerView.getChildLayoutPosition(child)
This will return the position of the view in the recycler view.
Here child is the View that registers the click event.
A full click listener code can be similar to:
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
}
});

RecyclerView OnClick not working

I have made a horizontal recyclerview inside a fragment. Now when I click on any item I don't see the on click listener working. Here is my code for the Adapter class:
public class FeaturedProductsAdapter extends RecyclerView.Adapter<FeaturedProductsAdapter.CustomViewHolder> {
private List<FeaturedProductInfo> feedItemList;
private Context mContext;
public FeaturedProductsAdapter(Context context, List<FeaturedProductInfo> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView imageView;
protected TextView textView,priceView;
private Context context;
public CustomViewHolder(View view,Context context) {
super(view);
this.context=context;
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView = (TextView) view.findViewById(R.id.prodTitle);
this.priceView = (TextView) view.findViewById(R.id.prodPrice);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getLayoutPosition(); // gets item position
Log.e("Check", position + "");
FeaturedProductInfo user = feedItemList.get(position);//[position];
// We can access the data within the views
Intent intent = new Intent(context, ProductDescription.class);
intent.putExtra("id", user.getId());
mContext.startActivity(intent);
}
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.featured_product_list_item_card, null);
Context context = viewGroup.getContext();
CustomViewHolder viewHolder = new CustomViewHolder(view,context);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeaturedProductInfo feedItem = feedItemList.get(i);
//Download image using picasso library
if(!feedItem.getUrl().contains("."))
{
feedItem.setUrl("nothing");
}
Picasso.with(mContext).load(feedItem.getUrl())
.error(R.drawable.unavailable)
.placeholder(R.drawable.unavailable)
.resize(110,110)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText(feedItem.getTitle());
customViewHolder.priceView.setText(feedItem.getPrice());
//Log.e("Featured: ","SET");
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}
I think I am not getting how to use the view holder properly. While I have used the same code for recyclerView in another activities and it works like charm.
1.Simple Click Handler within ViewHolder
RecyclerView does not have special provisions for attaching click handlers to items unlike ListView which has the method setOnItemClickListener(). To achieve a similar effect, we can attach click events within the ViewHolder within our adapter:
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
// ...
// Used to cache the views within the item layout for fast access
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView tvName;
public TextView tvHometown;
private Context context;
public ViewHolder(Context context, View itemView) {
super(itemView);
this.tvName = (TextView) itemView.findViewById(R.id.tvName);
this.tvHometown = (TextView) itemView.findViewById(R.id.tvHometown);
// Store the context
this.context = context;
// Attach a click listener to the entire row view
itemView.setOnClickListener(this);
}
// Handles the row being being clicked
#Override
public void onClick(View view) {
int position = getLayoutPosition(); // gets item position
User user = users.get(position);
// We can access the data within the views
Toast.makeText(context, tvName.getText(), Toast.LENGTH_SHORT).show();
}
}
// ...
}
Another way is my preferred way.. but this is also a fine way to go about it.
My onBindViewHolder
#Override
public void onBindViewHolder(CategoryViewHolder holder, int position) {
Category category = mCategories.get(position);
holder.tvTitle.setText(category.getTitle());
holder.tvDescription.setText(category.getDescription());
holder.rlContainer.setOnClickListener(mClickListener);
holder.rlContainer.setTag(holder);
}
My class level (Adapter object of View.OnClickListner)
View.OnClickListener mClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
CategoryViewHolder holder = (CategoryViewHolder) view.getTag();
int position = holder.getAdapterPosition();
startAppointmentBookingFor(mCategories.get(position));
}
};
so basically attach the listener to any view in your holder (I try to put it on container only), then extract it out on the onclick and handle positions etc.
In ‘CustomViewHolder’ below ‘super(view)’ add
view.setOnClickListener(this)
You’re done
Should work.
Make the following changes to your Adapter:
public class FeaturedProductsAdapter extends RecyclerView.Adapter<FeaturedProductsAdapter.CustomViewHolder> {
private List<FeaturedProductInfo> feedItemList;
private Context mContext;
private OnItemClickListener onItemClickListener;
public FeaturedProductsAdapter(Context context, List<FeaturedProductInfo,OnItemClickListener onItemClickListener> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
this.onItemClickListener = onItemClickListener;
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView imageView;
protected TextView textView,priceView;
private Context context;
public CustomViewHolder(View view,Context context) {
super(view);
this.context=context;
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView = (TextView) view.findViewById(R.id.prodTitle);
this.priceView = (TextView) view.findViewById(R.id.prodPrice);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onItemClickListener.onItemClick(getLayoutPosition());
Log.e("Check", position + "");
FeaturedProductInfo user = feedItemList.get(position);//[position];
// We can access the data within the views
Intent intent = new Intent(context, ProductDescription.class);
intent.putExtra("id", user.getId());
mContext.startActivity(intent);
}
}
public interface OnItemClickListener{
void onItemClick(int position);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.featured_product_list_item_card, null);
Context context = viewGroup.getContext();
CustomViewHolder viewHolder = new CustomViewHolder(view,context);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeaturedProductInfo feedItem = feedItemList.get(i);
//Download image using picasso library
if(!feedItem.getUrl().contains("."))
{
feedItem.setUrl("nothing");
}
Picasso.with(mContext).load(feedItem.getUrl())
.error(R.drawable.unavailable)
.placeholder(R.drawable.unavailable)
.resize(110,110)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText(feedItem.getTitle());
customViewHolder.priceView.setText(feedItem.getPrice());
//Log.e("Featured: ","SET");
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}

Categories

Resources