In an Android app, I have a dynamic viewPager, that may display a dynamic number of fragment (the fragment number is fixed before its instantiation). This viewPager is composed of 4 (fixed number) subViewPager. Every subViewPager can hold 1-5 fragments. It means that the whole count of fragment can reach up to 20 items.
For Info : A fragment can be just a set of fields, up to a canvas driven view, where the user interact with touching, added with bitmap displaying
I tried a first implementation by using a FragmentPagerAdapter (for main and subs viewpagers), it worked fine, but it took to much memory (120 MB of allocated heap memory)
I’m now using a FragmentStatePagerAdater to decrease the memory allocation
My problem, is that the subViewPager, which is handled in the Fragment of the mainViewPager, may be killed over navigation (this is what expected by statepageradapter to free memory) (they are initialized in OnCreateView).
=> The point is that I need that object to be able to swipe with a button :
For passing to the next fragment, I need to access to the mainViewPager, then the subViewPager of the current item of the mainViewPager in order to inc the current visible fragment.
The issue is that the holding fragment of the subViewPager may be/is killed, so the viewPager is null. Where and how handle the subviewpager to enable accessing subviewpager PLUS enable freeing memory by killing the unvisible fragments.
Here is a code part :
public class MySubViewPagerFragment extends Fragment {
private MySubFragmentPagerStateAdapter mSubPagerStateAdapter;
private ViewPager mPagerSub;
private TitlePageIndicator mIndicatorSub;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.vp_sub, container, false);
int id = getArguments().getInt("id");
// Creation de l'adapter
mSubPagerStateAdapter = new MySubFragmentPagerStateAdapter(getChildFragmentManager(), ((MainActivity) getActivity()).getConfigList().get(id));
// Creation du Pager
mPagerSub = (ViewPager) v.findViewById(R.id.vp_sub);
// Affectation de l'adapter au ViewPager
mPagerSub.setAdapter(this.mSubPagerStateAdapter);
TitlePageIndicator indicator = (TitlePageIndicator) v.findViewById(R.id.tpi_sub);
indicator.setViewPager(mPagerSub);
mIndicatorSub = indicator;
return v;
}
public boolean swipNextFragment() {
boolean result = false;
int c = mPagerSub.getCurrentItem();
if (c < (mPagerSub.getAdapter().getCount() - 1)) {
result = true;
new Handler().post(new Runnable() {
@Override
public void run() {
mPagerSub.setCurrentItem(mPagerSub.getCurrentItem() + 1);
}
});
}
return result;
}
}
I have tried to put the subViewPager at the activity level, but nothing has been solved.
Do you had any commun use case / solution or advise ?
Here is an example project with the same architecture. https://github.com/afaucogney/NestedAndroidViewPagers
PS: feel free to push me some advice on other optimisation if you see some.