Issue
I Use a Activity that holds a Fragment Inside That Fragment I have an other Fragment that holds ViewPagger2 now when apps open its should display first child of ViewPagger2 and also lode only that data but its not happening its loads two childs that make my app slow how to solve this issue.
Solution
It's the default behaviour of the viewPager2 to load adjacent pages for smoother animation. But you can override the default offscreen page limit by using viewpager2 setOffscreenPageLimit
method.
In kotlin use
viewPager2.offscreenPageLimit = PAGE_COUNT
This will load that specified number of pages in advance. But, this PAGE_COUNT
cannot be less than 1
which means, It'll still load your second fragment. But, It shouldn't slow down your app as you've mentioned.
If you are doing any network request then you can set registerOnPageChangeCallback
for viewPager2 and override onPageSelected
, then do the network request only when that fragment is selected.
As onPageSelected(position: Int)
only gives us the position of the selected page, but not the fragment itself, so we have to retrieve the selected fragment using childFragmentManager
and then trigger our network load request.
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
if (childFragmentManager.fragments.size > position) {
if(position == 1) { // for second fragment
val fragment = childFragmentManager.fragments[position] as SecondFragmentClassName
fragment.loadNetworkData()
}
}
}
})
For multiple fragments you can use when
statement accordingly.
Answered By - Praveen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.