Passing all recyclerview items from Activity1, into Activity2 recyclerview item - java

I have ActivityCourses and ActivityNewCourse. ActivityCourses include a list (recyclerview) of custom courses that user make, and ActivityNewCourse obviously is the activity where the user makes those custom courses.
ActivityNewCourse contains primitive data (course name and number of holes)
those are the data, which I pass to ActivityCourses, and make new item there in its recyclerview (so the new items name is that course name which is passed from ActivityNewCourse).
The problem I have is that ActivityNewCourse also contains recyclerview, and that contains obviously unique items. I need to get all those items, from ActivityNewCourse, and get them STORED (not shown) in that same item, where I send primitive data in ActivityCourses.
I've tried to use interface in my NewCourseAdapter, to pass those items from ActivityNewCourse recyclerview, to my ActivityCourses item, but the problem is that I need all of them items, not just 1. and also that button "Save Course" which user clicks to obviously save all the data from ActivityNewCourse, is outside of the recyclerview, where those items are located.
HERE IS MY NEW COURSE ADAPTER
public class NewCourseAdapter extends RecyclerView.Adapter<NewCourseAdapter.NewCourseViewHolder> {
private ArrayList<NewCourseItem> mNewCourseList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onMinusClick(int position);
void onPlusClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class NewCourseViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView1, mTextView2;
public ImageView mImageView1, mImageView2;
public NewCourseViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.hole_number);
mTextView2 = itemView.findViewById(R.id.par_number);
mImageView1 = itemView.findViewById(R.id.item_minus_btn);
mImageView2 = itemView.findViewById(R.id.item_plus_btn);
mImageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onMinusClick(position);
}
}
}
});
mImageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onPlusClick(position);
}
}
}
});
}
}
public NewCourseAdapter(ArrayList<NewCourseItem> newCourseList) {
mNewCourseList = newCourseList;
}
#NonNull
#Override
public NewCourseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_course_item, parent, false);
NewCourseViewHolder evh = new NewCourseViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull NewCourseViewHolder holder, int position) {
NewCourseItem currentItem = mNewCourseList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
holder.mImageView1.setImageResource(currentItem.getImageMinus());
holder.mImageView2.setImageResource(currentItem.getImagePlus());
}
#Override
public int getItemCount() {
return mNewCourseList.size();
}
}
HERES HOW I PASS PRIMITIVE DATA FROM ACTIVITYNEWCOURSE TO ACTIVITYCOURSES
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
courseName = findViewById(R.id.course_name_input);
number = findViewById(R.id.number_of_holes_number);
String intentCourseName = courseName.getText().toString().trim();
String holeNumber = number.getText().toString().trim();
Intent intent = new Intent(ActivityNewCourse.this, ActivityCourses.class);
intent.putExtra("COURSENAME", intentCourseName);
intent.putExtra("HOLENUMBER", holeNumber);
startActivity(intent);
}
});
HERES HOW ACTIVITYCOURSES RESIVE THE DATA
public void addItem() {
if (getIntent().getStringExtra("COURSENAME") != null) {
mCourselist.add(new CoursesItem(getIntent().getStringExtra("COURSENAME"), "Holes:", getIntent().getStringExtra("HOLENUMBER"), R.drawable.ic_delete));
}
}
I'm not sure if this code helped or not...
Am I somehow be able to send the whole arraylist from ActivityNewCourse, when save button been clicked? I don't know, I'm kinda dead end and I have no clue what to do, so any suggestions on what to do in this situation would help...

Have you tried using intent.putStringArrayListExtra("ARRAYNAME", arrayName);
try putting your data in an ArrayList and send it like this:
Intent intent = new Intent(ActivityNewCourse.this, ActivityCourses.class);
intent.putStringArrayListExtra("ARRAYNAME", arrayName);
startActivity(intent);
and the retrieve it like this:
ArrayList<String> listOfData = getIntent().getStringArrayListExtra("ARRAYNAME");
Hope it helps.
updated
Using Serializable:
first extend NewCourseItem to Serializable then:
Bundle bundle = new Bundle();
bundle.putSerializable("KEYNAME", new NewCourseItem("str1", "str2", "imglink", "imglink"));
intent.putExtras(bundle);
startActivity(intent);
retrieve it like this:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
NewCourseItem item = (NewCourseItem)bundle.getSerializable("KEYNAME");

Related

Delete item in RecyclerView works only once

When I delete an item from the RecyclerView, I am no longer able to delete another item. When I make an item I am also unable to delete that item and any other item in the RecyclerView.
Below is the code.
Home.java:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
itemImage = findViewById(R.id.image_holder);
itemName = findViewById(R.id.add_item_name);
itemPrice = findViewById(R.id.add_price);
itemDesc = findViewById(R.id.add_desc);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
addPhotoButton = findViewById(R.id.getCameraBtn);
addFileButton = findViewById(R.id.getGalleryBtn);
imageView = findViewById(R.id.image_holder);
addPhotoButton.setOnClickListener(this);
addFileButton.setOnClickListener(this);
itemList = new ArrayList<Item>();
// add item for testing
itemList.add(new Item(R.drawable.ic_logo, "Baby Stroller", "A stroller for baby", "59.99"));
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
adapter = new ItemAdapter(itemList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
#Override
public void onEditClick(int position) {
editItem(position);
}
});
}
// log out back to start page
public void goToStart(View view){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.getCameraBtn:
//post a photo from the camera
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_CODE);
break;
case R.id.getGalleryBtn:
//post an image
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*"); //anything that is image related
startActivityForResult(galleryIntent, GALLERY_CODE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK) {
if (data != null) {
imageUri = data.getData(); //we have the actual path
imageView.setImageURI(imageUri); //show image
}
} else if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
public void addItem(View view){
if(itemName.getText().toString().trim().length() != 0 || itemPrice.getText().toString().trim().length() != 0 || itemDesc.getText().toString().trim().length() != 0){
itemList.add(new Item(R.drawable.ic_logo, itemName.getText().toString(), itemPrice.getText().toString(), itemDesc.getText().toString()));
adapter = new ItemAdapter(itemList);
recyclerView.setAdapter(adapter);
itemName.setText("");
itemPrice.setText("");
itemDesc.setText("");
}
else{
Toast.makeText(Home.this, "All fields must be filled when creating a new item.",
Toast.LENGTH_LONG).show();
}
}
public void removeItem(int position){
itemList.remove(position);
adapter.notifyItemChanged(position);
}
ItemAdapter.java:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{
private ArrayList<Item> ItemList;
private OnItemClickListener Listener;
public void setOnItemClickListener(OnItemClickListener listener) {Listener = listener;}
public interface OnItemClickListener{
void onDeleteClick(int position);
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView item_image;
public TextView item_name;
public TextView item_desc;
public TextView item_price;
public ImageView deleteBtn;
public ImageView editBtn;
public ViewHolder(#NonNull View itemView, OnItemClickListener listener) {
super(itemView);
item_image = itemView.findViewById(R.id.item_image);
item_name = itemView.findViewById(R.id.item_name);
item_desc = itemView.findViewById(R.id.desc);
item_price = itemView.findViewById(R.id.price);
deleteBtn = itemView.findViewById(R.id.delete_item);
editBtn = itemView.findViewById(R.id.edit_item);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onDeleteClick(position);
}
}
}
});
}
}
public ItemAdapter(ArrayList<Item> itemList) {ItemList = itemList;}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v, Listener);
return vh;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Item currentItem = ItemList.get(position);
holder.item_image.setImageResource(currentItem.getItemImage());
holder.item_name.setText(currentItem.getItemName());
holder.item_desc.setText(currentItem.getItemDesc());
holder.item_price.setText(currentItem.getItemPrice());
}
#Override
public int getItemCount() {
return ItemList.size();
}
}
Item.java:
public class Item {
private int itemImage;
private String itemName;
private String itemDesc;
private String itemPrice;
public Item(int itemImage, String itemName, String itemDesc, String itemPrice){
this.itemImage = itemImage;
this.itemName = itemName;
this.itemDesc = itemDesc;
this.itemPrice = itemPrice;
}
public int getItemImage(){return itemImage;}
public String getItemName(){return itemName;}
public String getItemDesc(){return itemDesc;}
public String getItemPrice(){return itemPrice;}
}
When the user clicks the delete button, it will work the first time and remove that particular item but when another item needs to be removed, the button is not responding. The same happens when the user adds an item and is unable to delete any items. Not really sure what could cause this. Thanks.
Edit:
The delete function works correctly when I hardcode items into the RecyclerView. It is only when adding a new item, it doesn't work anymore including the hardcoded items.
In Home.java, you are setting the click listener:
adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {...}
In addItem(), you are creating a new adapter:
adapter = new ItemAdapter(itemList);
The problem is that you never set a click listener on this new adapter.
I would consider not creating a new adapter but calling a notify method to alert the adapter to a new item.
Try to change adapter.notifyItemChanged(position); to adapter.notifyItemRemoved(position);
You are telling the adapter that one item is changed, instead of that use:
notifyDataSetChanged()
this should reload all items

Do not treat position as fixed; only use immediately

I have this error in my code:
Do not treat position as fixed; only use immediately and call holder.getAdapterPosition() to look it up later.
I even used holder.getAdapterPosition() in the position place, but it still keeps crashing the app when I click the items.
MusicAdapter(Context mcontext, ArrayList<MusicFile> mfiles) {
this.mfiles = mfiles;
this.mcontext = mcontext;
}
#Override // androidx.recyclerview.widget.RecyclerView.Adapter
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(this.mcontext).inflate(R.layout.music_items, parent, false));
}
public void onBindViewHolder( final MyViewHolder holder, int position) {
holder.file_name.setText(this.mfiles.get(position).getTitle());
byte[] image = getAlbumArt(this.mfiles.get(position).getPath());
if (image != null) {
Glide.with(this.mcontext).asBitmap().load(image).into(holder.album_art);
} else {
Glide.with(this.mcontext).load((int) R.drawable.ic_launcher_background).into(holder.album_art);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MusicAdapter.this.mcontext, PlayerActivity.class);
intent.putExtra("position", holder.getAdapterPosition());
MusicAdapter.this.mcontext.startActivity(intent);
}
});
}
#Override // androidx.recyclerview.widget.RecyclerView.Adapter
public int getItemCount() {
return this.mfiles.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView album_art;
TextView file_name;
LinearLayout linearLayout;
public MyViewHolder(View itemView) {
super(itemView);
this.file_name = (TextView) itemView.findViewById(R.id.music_file_name);
this.album_art = (ImageView) itemView.findViewById(R.id.music_img);
linearLayout = itemView.findViewById(R.id.linear_layout);
}
}
private byte[] getAlbumArt(String uri) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(uri);
byte[] art = retriever.getEmbeddedPicture();
retriever.release();
return art;
}
}
Imagine that we have a RecyclerView that will display 10 items so it will create 10 items and call onBindView for those 10 items and pass the positions from 0 to 9, so if you fixed the position by using it to handle user clicks and later you added an item at position 0 and notified the data set that you inserted a new item by notifyItemInserted() the RecyclerView will create a new item with position 0 and pass it to the layout but the pre created ones still have the old positions and if you logged those positions you will have 00123…9 which is not true it should be 0123…10. Here come the power of holder.getAdapterPosition().
#Override
public void onBindViewHolder(#NonNull GalleryViewAdapter holder,final int position) {
Glide.with(context).load(images.get(position)).into(holder.imageView);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, FullImageview.class);
intent.putExtra("image", images.get(holder.getAdapterPosition()));
context.startActivity(intent);
}
});
}
now its fine to use holder.getAdapterPosition for user click event
notice that i used getAdapterPosition to bind data and used getLayoutPosition to tell the user the position of the pressed item.

Display specific Array for specific item when click on it using Recyclerview "ItemClickListener"

I Have a problem with my Adapter, First I want to display a different Array of data for every item in RecyclerView when clicking on it like this...
Item 1 "display" Array one
Item 2 "display" Array two
And so on... My data will be display in ViewPager on Activity, so I want to pass the data from the RecyclerView Adapter that have the items to the Activity that will display the data "The Activity has Viewpager that will get the data"
So that's what I tried before but it is just open the activity and not display the data.
First Her's My RecyclerView Adapter that has the items And the data
RecyclerViewItems.java
public class RecyclerViewQuran extends RecyclerView.Adapter<RecyclerViewQuran.ViewHolder> {
private ArrayList<QuranListDetail> item;
/* My data "Arrays" */
// first Array for First item
public static int[] mImageIds = new int[]
{
R.drawable.test_heart, R.drawable.test_home,
R.drawable.test_image, R.drawable.test_image, R.drawable.test_video,
};
// second Array for second item
public static int[] mImageIds2 = new int[]
{
R.drawable.nabawe_image_full, R.drawable.nabawe_image_full,
R.drawable.nabawe_image_full, R.drawable.nabawe_image_full, R.drawable.nabawe_image_full,
};
public RecyclerViewQuran(FragmentActivity activity, ArrayList<QuranListDetail> items) {
this.item = items;
}
#Override
public RecyclerViewQuran.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_quran, viewGroup, false));
}
#Override
public void onBindViewHolder(RecyclerViewQuran.ViewHolder holder, final int position) {
holder.itemTitle.setText(item.get(position).getSurahName());
holder.itemDetail.setText(item.get(position).getSurahDetail());
holder.itemNumber.setText(item.get(position).getSurahNumber());
// click listener to open new activity "shurah"
holder.itemClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
// Array 1
if (position == 0) {
int image = mImageIds[position];
Intent intent = new Intent(context, QuranSurahDisplay.class);
intent.putExtra("imageDisplay", image);
context.startActivity(intent);
}
// Array 2
else if (position == 1) {
int image = mImageIds2[position];
Intent intent = new Intent(context, QuranSurahDisplay.class);
intent.putExtra("imageDisplay", image);
context.startActivity(intent);}
}
});
}
#Override
public int getItemCount() {
return item.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView itemTitle;
private TextView itemDetail;
private TextView itemNumber;
private View itemClick;
public ViewHolder(View view) {
super(view);
itemTitle = view.findViewById(R.id.surah_name);
itemDetail = view.findViewById(R.id.surah_detail);
itemNumber = view.findViewById(R.id.surah_number);
itemClick = view.findViewById(R.id.item_click);
}
}
.
Second my ViewPagerAdapter.java
public class ViewPagerSurahAdapter extends PagerAdapter {
private Context mContext;
private int[] mImageIds;
public ViewPagerSurahAdapter(Context context, int[] mImageIds) {
mContext = context;
this.mImageIds = mImageIds;
}
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(#NotNull View view, #NotNull Object object) {
return view == object;
}
#NotNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
// PhotoView to zoom in the image "Instaded of ImageView"
PhotoView imageView = new PhotoView (mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, #NotNull Object object) {
container.removeView((ImageView) object);
}
}
Third My Activity that will display the data in the ViewPager, My problem here I don't know how to pass the data in the ViewPager, Her's what I did.
public class QuranSurahDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_surah);
final Intent intent = getIntent();
if (intent.hasExtra("imageDisplay")) {
ViewPager viewPager = findViewById(R.id.view_pager_quran_fateha);
int[] url = intent.getIntArrayExtra("imageDisplay");
//ViewPager
ViewPagerSurahAdapter adapter = new ViewPagerSurahAdapter(this,url);
viewPager.setAdapter(adapter);
}
}
}
If you have any questions u can write it in the comments and I will be explaining to you.

How to transfer string from TextView to main activity with onClick listener

I want to create an onclick listener that reads the String from one TextView and then I somehow pass that string onto the main activity in order to open a third activity
So my main activity looks like this
public class AdvancedResults extends AppCompatActivity {
private RecyclerView mRecyclerView;
private AdvancedAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
private ArrayList<String> saved_recipes_with_ingredients = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_results);
advancedList.add(new AdvancedItem(R.drawable.ic_android, "test1", "test2");
advancedList.add(new AdvancedItem(R.drawable.ic_android, "test3", "test4");
mRecyclerView = findViewById(R.id.recyclerView1);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new AdvancedAdapter(advancedList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new AdvancedAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
// I want to open a new activity and append the string from the TextView here (maybe with get/set)
}
});
}
And my recycler adapter looks like this
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageViewADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
//how do I get the string from the TextView and pass it onto the main class?
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
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, mListener);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mImageView.setImageResource(currentItem.getImageResource());
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
i'm just not sure how im supposed to do that and what method to use.
So if you want the text from the text view you do:
String text = textViewId.getText();
But in your case you want to add the text for each one of the views on the list
So on the adapter how make a on click listener:
if (listener != null) {
int position = getAdapterPosition();
String text = mTextView1.getText();
Intent i = new Intent(getApplicationContext(), YourActitivity.class);
i.putExtra("nameYouWant", text)
startActivity(i);
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
Now on your activity :
String text = intent.getStringExtra("nameYouWant");
You can use interface to pass the second String param. So just add one String param like this -
public interface OnItemClickListener {
void onItemClick(int position, String text);
}
And in adapter pass the string on click of the item along with the position
listener.onItemClick(position, mTextView1.getText().toString());
And in the activity, you will receive the String text, from there you can pass it to ThirdActivity via bundle.
mAdapter.setOnItemClickListener(new AdvancedAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position, String textData) {
Intent i = new Intent(this, ThirdActivity.class);
i.putExtra("TEXT_KEY", textData);
}
});
Hope it will help!!

Differentiate columns in Recyclerview clicks

to begin I would thanks those who help noobi dev like me :p! Let's say that I have a Recyclerview in which every unit element has two images. Actually I am able to find the indice of the unit element clicked to fire the good evenment thanks to this little trick in MyAdapter:
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
final MyHolder holder = new MyHolder(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(v, holder.getAdapterPosition());
}
});
return holder;
}
Then I start the event this way in the activity:
MyAdapter adapter = new MyAdapter(this, countryCollection.getCountryArray(), new CustomItemClickListener() {
#Override
public void onItemClick(View v, int position) {
//Launch the events
ArrayList<String> languageCodeArray = countryCollection.getLanguageCodeArray();
ArrayList<String> countryIdArray = countryCollection.getCountryIdArray();
if(position >0){
String languageCode = languageCodeArray.get(position-1);
String countryId = countryIdArray.get(position-1);
Intent intent = new Intent(context, LetsSpeakActivity.class);
intent.putExtra("country_id", countryId);
intent.putExtra("language_code", languageCode);
startActivity(intent);
}
}
});
rv.setAdapter(adapter);
But how can I différentiate the two images of my RecyclerView in order to fire the good event? I've been searching for a while how to differentiate a click on the left or right side of the screen but it is obviously not the right way to do ! Any help would be lovely, I am really stuck...
Supposing you have defined both ImageView in your MyHolder class, you could set OnClickListener on both of them in your holder constructor :
public class MyHolder extends RecyclerView.ViewHolder {
public ImageView imageLeft;
public ImageView imageRight;
public CustomItemClickListener listenerLeft;
public CustomItemClickListener listenerRight;
public MyHolder(View v, CustomItemClickListener listenerLeft, CustomItemClickListener listenerRight) {
super(v);
this.listenerLeft = listenerLeft;
this.listenerRight = listenerRight;
imageLeft = v.findViewById(R.id.image_left);
imageRight = v.findViewById(R.id.image_right);
imageLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listenerLeft.onItemClick(v, getPosition());
}
});
imageRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listenerRight.onItemClick(v, getPosition());
}
});
}
}
while injecting both listener in onCreateViewHolder :
#Override
public MyAdapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
return new MyHolder(v, mImageLeftListener, mImageRightListener);
}
You can introduce both of these listener in your Adapter constructor like you did with listener
Or if you want to pass only one listener, you can define your CustomItemClickListener interface with 2 methods (or just 1 with an additional param to differentiate the image clicked) :
public interface CustomItemClickListener {
void onLeftImageClick(View view, int position);
void onRightImageClick(View view, int position);
}

Categories