Android – How to call getFragmentManager on Recycler.Adapter

androidandroid-fragments

I am converting ListView of my app to RecyclerView. On ListView, it was very easy to implement OnClickListener but in RecyclerView, we have to do it in adapter. I want to open a new Fragment when user clicks on a item. To do this I have to call FragmentManager in adapter which I am not able to do.
This is my code of RecyclerAdapter:

public ListItemViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);
            description = (TextView) itemView.findViewById(R.id.description);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            //Call FragmentManager and add Fragment to it.
            }
        }

So, how to call FragmentManager and add Fragments in it. Is there any better way than this like sendingBroadcast or any other method.

Best Solution

You just need an activity context passed in your constructor. Be sure to call new Adapter(this,...) from activities and new Adapter(getActivity(),...) from fragments.

private Context context;

@Override
public void onClick(View v) {
    FragmentManager manager = ((AppCompatActivity)context).getSupportFragmentManager();
}