0

I have a nav_graph, where Fragment 1 and Fragment 2 are defined. Fragment1 has view pager with 3 tabs and each tab has recyclerview.

How can i navigate to Fragment 2 on item click of recyclerview ?

Fragment->ViewPager->Recyclerview->ClickAction.

Mohammed Imran N
  • 1,279
  • 1
  • 11
  • 26
  • Call `navigate`? – ianhanniballake Sep 30 '22 at 00:12
  • Have you provided a certain `callback` like a `lambda parameter` or an `interface listener` to your adapter so your items can communicate things back to its host component (fragment)? – z.g.y Sep 30 '22 at 00:34
  • is there any way to use action of Fragment1 inside recyclerview ? other than callback ? – Mohammed Imran N Sep 30 '22 at 04:28
  • @Mohammed, it seems you can not use nav component with fragments which not affect BackStack (like tabs and viewpager). For the reference https://stackoverflow.com/questions/54298137/viewpager-with-navigation-architecture-components. There would be an issue to communicate back to Fragment 1 with ViewPager by NavGraph. – Gleichmut Sep 30 '22 at 08:56

1 Answers1

0

In recyclerview's fragment, simply call requireParentFragment().findNavController().navigate(/* destination */) to navigate to Fragment2.

Besides, you should pass a lambda into your recycler view adapter and then pass it into your view holder for using it (i recommend this way).

You can read more about this in the sample code below.

class YourRecyclerViewAdapter(..., private val onItemClick: () -> Unit) : RecyclerView.Adapter<YourViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup) = YourViewHolder(onItemClick)
    
    override fun onBindViewHolder(holder: YourViewHolder, position: Int) {
        holder.bind(...)
    }
}
    
class YourViewHolder(..., private val onItemClick: () -> Unit) : RecyclerView.ViewHolder(...) {
    fun bind(...) {
        // Use onItemClick here...
    }
}
    
class RecyclerViewFragment : Fragment() {
    override fun onViewCreated(view: View, saveInstanceState: Bundle?) {
        val adapter = YourRecyclerViewAdapter(...) {
            requireParentFragment().findNavController().navigate(...)
        }
        yourRecyclerView.adapter = adapter
    }
}
Anh Tran
  • 131
  • 1
  • 5