Passing data from a RecyclerView to Fragment

Viewed 59

I am currently creating an application that consists of a Fragment, an Adapter for a RecyclerView, and a RecyclerView which is accessed through the fragment. I need data to be passed from the RecyclerView back to the fragment however am unable to do so as the Fragment isn't identified through the Intent. When the user selects an item from the RecyclerView this item should be then passed through to the fragment. I have the RecyclerView using onBackPressed() to navigate back to the fragment which works fine. However, no data seems to pass. Please see below what I currently have in the onItemClick:

@Override
public void onItemClick(View view, int position) {
    // Need to pass data through to Fragment, however unable to do so as it's not identified
    // within the Intent
    onBackPressed();
}
1 Answers

If you want to pass data to your Fragment, then i think you should do an OnItemClickListener interface in your RecyclerViewAdapter and have your Fragment implement it. The Fragement should register itself to the onItemClickListeners in the RecyclerViewAdapter. Then you should be able to pass your Fragment the clicked Item.

This goes into your RecyclerViewAdapter's class:

 class RecyclerViewAdapter{
 //...
        interface OnItemClickListener {
            void onItemClick(Item item); //replace the item with whatever you want to pass to the fragment
        }

        List<OnItemClickListener> onItemClickListeners  = new ArrayList<>();

        public void addOnItemClickListener(OnItemClickListener listener){
            onItemClickListeners.add(listener);
        }
        @Override
        public void onItemClick(View view, int position) {

            for(OnItemClickListener listener : onItemClickListeners) {
                listener.onClick(item);
            }
            onBackPressed();
        }
     //...
    }

This goes in your Fragment's class:

class Fragment implements RecyclerViewAdapter.OnItemClickListener {

    //...
    //Somewhere in your fragment where you create your RecyclerViewAdapter
    recyclerViewAdapter.addOnItemClickListener(this);
    //...
    @Override
    public void onItemClick(Item item) {
        //now data is passed to your Fragment
    }
}

Hope that this helps solving the problem you are having.

Related