0

I am making a simple app with a recycler containing a list of items, and when an item is clicked, it needs to navigate to a new separate page for that item.(Note that the recycler view with list of items and the item page are both fragments and the navigation needs to happen without starting a new activity)

I have set up the NavHostFragment in MainActivity and the onClickListener to get the item clicked in the onBindViewHolder method of Adapter classs of the fragment with recycler view. I cannot figure out how to call the navController in MainACtivity within the onClickListener method in Adapter class to navigate to the item fragment, or is there any other way to do this? I am newbie android studio dev! Please help, thanks!

Kalindu
  • 111
  • 2
  • 9
  • It is preferred to avoid putting logic in the Adapter. The most straight forward solution would be to have the Activity implement a listener interface for the Adapter. See example here: https://stackoverflow.com/a/33031936/2649154 – gioravered Sep 04 '22 at 10:53

1 Answers1

1

You can simply implement an interface to make communication between fragment and adapter.

Suppose there is FragmentA, FragmentB, and an Adapter.

FragmentA and adapter are related and you want to move from FragmentA to FragmentB. So you connect FragmentA with the adapter using an interface listener. Handle the click event in the adapter and pass data from adapter to FragmentA and from override method in FragmentA call FragmentB using nav controller.

Here is simple example:

Listener:

public interface eventListener { void onEvent(int key, Object object); }

FragmentA:

class FragmentA : Fragment(), eventListener {

     override fun onEvent(key: Int, any: Any?) { // call FragmentB }

}

Adapter:

class Adapter(listener: WoovlyEventListener) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

    holder.btn.setOnClickListener{ listener.onEvent(0, null) }

    }
}

FragmentB:

class FragmentB : Fragment(){}
Thakar Sahil
  • 248
  • 1
  • 7