Avoiding onCreateView () when scrolling through tabs

I have an application with activity and 3 swipable tabs (snippets). I have some heavily crafted user interface elements inside tabs that take some time to create, and this is fine for the first run, but the views are recreated every time I scroll through them.

When I select a tab, another tab calls onStop (), and when I select the previous tab again, onCreateView () is called again, and the view is populated, which slows down and blocks the user interface stream.

What is the correct way to create fragments inside ONCE tabs and avoid re-creating their appearance when scrolling between other tabs?

+6
source share
3 answers

To add to what CommnosWare says, if you use a view pager, you can simply call mViewPager.setOffscreenPageLimit(3); to save all three in memory. But if your user interface is too heavy, you might notice some kind of bit. Therefore, try changing the UI setup code.

+16
source

I have some heavily crafted user interface elements inside tabs that take some time to create

If "some time" exceeds ~ 5 milliseconds, your application is broken and needs to be fixed. Use Traceview to pinpoint where you spend your time, and then repair issues so it takes less time for the main application stream.

What is the correct way to create fragments inside the tabs ONCE and avoid recreating their appearance when scrolling between other tabs?

AFAIK, the FragmentPagerAdapter should not have the effect you are describing (although the FragmentStatePagerAdapter will be). But, again, if you fix the onCreateView() performance onCreateView() , even the FragmentStatePagerAdapter will not post the issue.

+2
source

Just add the following code inside the main Fragment / Activity class where the TabAdapter is declared.

 viewPager.setOffscreenPageLimit(tabLayout.getTabCount()); 

Tab tabLayout and viewPager as follows

 TabLayout tabLayout = (TabLayout) root.findViewById(R.id.tab_layout); ViewPager viewPager = (ViewPager) root.findViewById(R.id.pager); 
0
source

Source: https://habr.com/ru/post/946412/


All Articles