I was trying to pass data from the Parent Activity to the viewPager, and I found a solution using findFragmentByTag but it returns Null and I'm not sure what I missed.
The example I found used a deprecated FragmentPagerAdapter and I think maybe that's why my implementation doesn't work, so I'm looking for a way forward.
(supportFragmentManager.findFragmentByTag(tag) as StopwatchFragment?)?.displayData(
min!!,
sec!!,
millis!!
)
is null
Main Activity
class MainActivity : AppCompatActivity(), StopwatchListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
...
binding.viewPagerMain.adapter = PageAdapter(supportFragmentManager, lifecycle)
}
...
override fun getTheTime(min: String?, sec: String?, millis: String?) {
val tag =
"android:switcher:" + R.id.view_pager_main.toString() + ":" + binding.viewPagerMain.currentItem
Log.d("Main", tag)
(supportFragmentManager.findFragmentByTag(tag) as StopwatchFragment?)?.displayData(
min!!,
sec!!,
millis!!
)
}
}
PageAdapter
class PageAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount() = 3
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> {
RepsFragment()
}
1 -> {
StopwatchFragment()
}
2 -> {
TimerFragment()
}
else -> {
RepsFragment()
}
}
}
}
This is valid for the
ViewPagernotViewPager2.In order to do that for
ViewPager2, you need:And this requires to have unique IDs for the pages, for simplicity you can set them as the
ViewPagerpositions; to do so overridegetItemId()of the adapter:And then the
pageIdwill be the current page (or any page position you want), and hence the tag would be: