ncapdevi / FragNav

An Android library for managing multiple stacks of fragments
1.5k stars 210 forks source link

How to send argument when switching tab #235

Open mochadwi opened 3 years ago

mochadwi commented 3 years ago

in the getRootFragment(index: Int) method, we can only declare a DestinationFragment.newInstance("hardcoded value1") without having to know how to send argument, e.g (from a deeplink):

fun iniFragNav() {
 val fragments = listOf(Fragment(), Fragment(), DestinationFragment())
 val deeplink = "example://destination/tab2"
 val tabName = Uri.from(deeplink).path.split[1] // a local variable

 bottomNavigation.setOnTabSelected { position: Int ->
   if (position == 2) DestinationFragment.newInstance(tabName)
 }
}
// DestinationFragment.kt

class DestinationFragment : Fragment() {

   companion object {
       fun newInstance(tabName: String): DestinationFragment {
             return DestinationFragment().putArgs { // an anko extension
                  putString("tab", tabName)
            }
       }
  }

 // e.g: init viewpager and set current item based on argument
 fun initViewPager() {
     viewpager.currentItem = when (arguments?.getString("tab")) {
          "tab1" -> 1
          "tab2" -> 2
          else -> 0
    }
 }
}

any reference to achieve the above approach? or maybe a workaround to send an argument via FragNavController.

our usecase is for a deeplink scheme to go into specific tab in DestinationFragment with ViewPager