Search code examples
androidandroid-fragmentsandroid-recyclerviewandroid-cardviewandroid-cards

How to pass data to fragment when click on cardview in onBindViewHolder?


Here is my adapter code and I want to pass data to the "ParticularFragment" Note : ParticularFragment extends Fragment

public class TopicsAdapter extends RecyclerView.Adapter<TopicsAdapter.ViewHolder> {

    private Context context;
    private ArrayList<QuoteItems> itemList;

    public TopicsAdapter(Context context, ArrayList<QuoteItems> itemList) {
        this.context = context;
        this.itemList = itemList;
    }

    @Override
    public TopicsAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_topics_recycler_view_items, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final TopicsAdapter.ViewHolder viewHolder, int i) {

        final QuoteItems quoteItems = itemList.get(i);
        viewHolder.txtQuote.setText(quoteItems.getQuote());

        viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

             //how to pass data to "ParticularFragment" from here
            }
        });
    }

    @Override
    public int getItemCount() {
        return itemList.size();
    }
    class ViewHolder extends RecyclerView.ViewHolder {

        public TextView txtQuote;
        public CardView cardView;

        public ViewHolder(View itemView) {
            super(itemView);
            txtQuote = (TextView) itemView.findViewById(R.id.txtQuote);
            cardView = (CardView) itemView.findViewById(R.id.cardView);
        }
    }
}

Solution

  • Add following code in your onclick

    ReciverFragment fragment = new ReciverFragment(); 
    Bundle args = new Bundle();
    args.putString("Your_Key", "Your_Value");
    fragment.setArguments(args);
    //Inflate the fragment
    context.getFragmentManager().beginTransaction().add(R.id.container, fragment).commit();
    

    Note: change

    private Context context;
    

    to

    private Activity context;
    

    and as parameter of TopicsAdapter constructor pass getActivity() from your fragment.