Answer the question
In order to leave comments, you need to log in
Viewpager loading all fragments?
Good morning, guys, I've been racking my brain for a day and I just can't figure out what the problem is.
At the bottom, I added the code, this one when it loads all the fragments at once, but I want it to be like this: The application opens, data is loaded only from "OneFragment", then scrolled through and loaded from "TwoFragment".
Tell me how to do it?
PagerAdapter.java
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
OneFragment tab1 = new OneFragment();
return tab1;
case 1:
TwoFragment tab2 = new TwoFragment();
return tab2;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("One"));
tabLayout.addTab(tabLayout.newTab().setText("Two"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition(), true);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("fragmentpage", String.valueOf(tab.getPosition()));
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Answer the question
In order to leave comments, you need to log in
by default the pager creates and stores 3 fragments, which is before the user, one before, one after.
this behavior can be changed by making setOffscreenPageLimit(int num)
but, I suppose, the interest is not idle? do you want to catch the event when the fragment appears in front of the user?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question