I'm creating a launcher application tailored to devices with D-Pads. When working with ViewPager2, I've had to work in D-Pad support in order to achieve proper page switching and focusing.
I've introduced Navigation components into my app so that I'd be able to navigate in and out of an app drawer. Unfortunately, after placing my ViewPager2 in a NavGraph and letting it be handled by the NavHost, the code I used to get a reference to the current page/fragment (childFragmentManager.findFragmentByTag("f${viewPager.currentItem}")) has since stopped working, consistently returning null.
The old code follows, which worked well when I didn't have a NavHost setup. psLis is a callback which was passed into HomeFragment (ListAdapter host/initializer), and from there passed into HomeAdapter (ListAdapter), which set up an OnKeyListener to call psLis on the leftmost/rightmost cells.
HomePager.kt (Contains the ViewPager2 instance, navigation indicator, 'dock', app drawer)
// .....
val psLis: (Char, Int) -> Unit = { direction, pos ->
val curItem = viewPager.currentItem
val TAG = "psLis"
Log.d(TAG, "Page-switch listener initiated.")
if (direction == 'l' && curItem > 0) {
viewPager.currentItem = curItem - 1
val curFragment = // Get page fragment
childFragmentManager.findFragmentByTag("f${viewPager.currentItem}")
Log.d(TAG, "curFragment is $curFragment")
if (curFragment is HomeFragment) {
curFragment.setFocus(pos + 3) // Set the focus within the same row
}
} else if (direction == 'r' && curItem < (NUM_PAGES - 1)) {
viewPager.currentItem = curItem + 1
val curFragment =
childFragmentManager.findFragmentByTag("f${viewPager.currentItem}")
Log.d(TAG, "curFragment is $curFragment")
if (curFragment is HomeFragment) {
curFragment.setFocus(pos - 3)
}
}
}
HomeFragment.kt (Hosts/initializes the homescreen ListAdapter)
// .....
fun setFocus(pos: Int) {
val child = binding.recyclerView.getChildAt(pos)
child.requestFocus()
}
Again, childFragmentManager.findFragmentByTag("f${viewPager.currentItem}") has only begun returning null after I let the ViewPager2 be handled by a NavHost.
parentFragmentManager.fragments returns the singular HomePager instance, and childFragmentManager.fragments returns a blank list.
I feel I've exhausted the more relevant-seeming functions, and I haven't been able to find anyone else facing this specific issue on StackOverflow or the general web. Any help/advice would be much appreciated. Cheers.
When using Navigation Component try using: