Reputation: 43
I'm using an app with a navigation drawer menu, and I want all of the fragments to be created when the app starts, as some of the fragments fetch data from a web service and I do not want the user to have to wait for all of the data to load right when they go to a screen. To work around this, I want to create all of the fragments at once and then hide them, and then afterwards display the correct fragment.
private void initFragments() {
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();
for (int i = 0; i < MAIN_FRAGMENTS; i++) {
fTransaction.add(R.id.frame_container, fragmentArray[i], fragmentTags[i]);
}
fTransaction.commit();
fManager.executePendingTransactions();
}
private void hideFragments(){
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();
for (int i = 0; i < MAIN_FRAGMENTS; i++) {
fTransaction.hide(fManager.findFragmentByTag(fragmentTags[i]));
}
fTransaction.commit();
fManager.executePendingTransactions();
}
My way to work around this was to just create all of the fragments and then hide them by calling
initFragments()
hideFragments()
However, I've noticed that when I run this on the emulator, on some devices it will correctly only show one Fragment, with the rest being added but hidden. But on some other devices, it will show all of the fragments overlaid ontop of eachother resulting in an ugly mess. Furthermore, when I use the app on a landscape device such as a tablet, the fragments will also overlap eachother as I have forced the app into a portrait only mode. Any ideas on the best way to go about this?
Upvotes: 1
Views: 957
Reputation: 923
Are you getting any errors?
I suspect some devices/versions might not support the findFragmentByTag() method, or the hide() method for that matter. Try looking into that.
With regard to your overlapping problem on tablets, try this: https://stackoverflow.com/a/11086185/2929693
Upvotes: 1