Answer the question
In order to leave comments, you need to log in
How to pass data from RecyclerView to a fragment that opens on click of list items?
There is a RecyclerView with several elements, each of which leads to the same fragment. Is it possible to pass data for a fragment through setArguments? (for example, so that when you click on the first element in the fragment, "text1" appears, when you click on the second element - "text2", etc.). How to do it?
public class GalleryGridAdapter extends RecyclerView.Adapter<GalleryGridAdapter.ViewHolder> {
private CompanyFragment mContext;
private ArrayList<CompanyObject> imageList;
public GalleryGridAdapter(CompanyFragment mContext, ArrayList<CompanyObject> imageList){
this.mContext=mContext;
this.imageList=imageList;
}
public interface ItemClickListener {
void onItemClick(int position);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_choose_company, parent, false);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CompanyMenuFragment newFragment = new CompanyMenuFragment();
((AppCompatActivity) itemView.getContext()).getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, newFragment)
.addToBackStack(null)
.commit();
}
});
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
CompanyObject image = imageList.get(position);
Glide.with(mContext).load(image.getCompanyImage()).into(holder.imageGallery);
}
@Override
public int getItemCount() {
if(imageList==null) return 0;
return imageList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageGallery;
public ViewHolder(View view) {
super(view);
imageGallery = itemView.findViewById(R.id.tile_picture);
}
}
}
public class CompanyObject {
public int companyImage;
public CompanyObject(int companyImage) {
this.companyImage = companyImage;
}
public int getCompanyImage() {
return companyImage;
}
public void setGalleryImage(int galleryImage) {
this.companyImage = galleryImage;
}
}
private void prepareData()
{
SimpleObject item = new SimpleObject(R.drawable.image);
recyclerList.add(item);
item = new SimpleObject(R.drawable.image1);
recyclerList.add(item);
item = new SimpleObject(R.drawable.image2);
recyclerList.add(item);
mAdapter.notifyDataSetChanged();
}
Answer the question
In order to leave comments, you need to log in
Add data to the fragment:
Bundle args = new Bundle();
args. putString("MY_TAG", value);
CompanyMenuFragment newFragment = new CompanyMenuFragment();
newFragment.setArguments(args);
Get the data in the fragment:
Bundle b = getArguments();
String s = b.getString("MY_TAG");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question