How to Open Fragment from Recyclerview Adapter

How to open fragment from RecyclerView Adapter?

Do two small changes in your code-


public CatAdapter(ArrayList<String> catUrlImage, ArrayList<String> cuteCatName, Context catContext, OnRecyclerViewItemClickListener listenerthis) {
this.catUrlImage = catUrlImage;
this.cuteCatName = cuteCatName;
this.catContext = catContext;
this.listenerthis = listenerthis;


private void initRecycleView() {
CatAdapter catAdapter = new CatAdapter(catArrayImageUrl, catArray, this, this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

thats it. Hope it will be helpful.

Jetpack navigation: How do I open a new fragment from a recyclerview adapter?

As navigation occurs among fragments, so normally you'd keep the fragment's the responsibility to do that.

As you told that adapter which can be used in multiple fragments, so it should be attached to a particular fragment at a time, which normally it's the fragment that instantiated it.

So, you can pass a listener interface to the adapter which is implemented by the fragment; where you can trigger its callback in the adapter whenever you want to navigate to another fragment in the nav graph.

This callback method will be executed at the fragment which already implements the listener, and you can normally use the traditional navigation code:


This way your adapter can be reused, and every time a fragment wants to reuse it, it should implements the listener.

Note: Probably you can pass an int argument to the listener callback that pass in the row number in the adapter back to the fragment so that you might decide to navigate to some other fragment.

This way you can keep the navigation only through fragments.

how to open a different fragment on recyclerview OnClick

So simplified version, here's my onbindVH:

public void onBindViewHolder(FeedsViewHolder holder, int position) {
final Feed item = mFeeds.get(position);

holder.imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

here's fragmentJump:

private void fragmentJump(Feed mItemSelected) {
mFragment = new Fragment2();
mBundle = new Bundle();
mBundle.putParcelable("item_selected_key", mItemSelected);
switchContent(, mFragment);

here's switchContent on the adapter:

public void switchContent(int id, Fragment fragment) {
if (mContext == null)
if (mContext instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) mContext;
Fragment frag = fragment;
mainActivity.switchContent(id, frag);


and lastly, here's the switchContent on MainActivity:

public void switchContent(int id, Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(id, fragment, fragment.toString());

I know it can still be simplified, but it works as is. I hope it helps. :)

Related Topics

Leave a reply