Reputation: 18108
i have a piece of code where i wish to just hide the current fragment so it doesnt destroy its view and then show a new one using this :
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.hide(oldFragment);
ft.show(newFragment);
ft.commit();
The issue is that when i execute the above code, it doesnt show any UI components.
if i do ft.replace(id,fragment);
it works but i do not want to remove the previous displayed fragment as i want to maintain the fragments and its views so i dont need to re-initialise it
Upvotes: 0
Views: 289
Reputation: 3147
Was your fragment initialized before calling this?
if (newFragment == null) {
// If not, instantiate and add it to the activity
ft.add(yourFragmentContainerId, newFragment,"tag");
} else {
// If it exists, simply attach it in order to show it
ft.show(newFragment);
}
Upvotes: 1
Reputation: 40734
Did you previously add newFragment
to some part of your Activity
's view hierarchy? If you just instantiate a Fragment
and tell it to show, it won't know where to show (unless it's a DialogFragment
, I guess). You need to use add(somelayoutid,fragment,"sometag")
for each Fragment
and then you can hide/show them as you'd like. You can also just continually use replace, rather than hide/show, if you don't need to keep your Fragment
's around while they're hidden.
"sometag" will be useful if you're handling rotation so you can retrieve a reference to each Fragment
after your Activity
is recreated, and then you can hide/show them as before.
Upvotes: 1