Issue
I have 3 fragments listed in the nav drawer all of which include a webview. By clicking items from the nav drawer, I want to switch between the fragments but also saving their states at the same time. Given code is the listener method for the nav drawer. How do I check if there are any existing instances of the fragment before instantiating a new one?
private void selectItem(int position) {
Fragment newFragment = new Fragment_1();
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
switch(position) {
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new Fragment_2();
break;
case 2:
break;
}
android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.content_frame, newFragment);
t.addToBackStack(null);
t.commit();
}
Solution
Well, you have to do it in 2 steps :
1/ Firstly, FragmentTransaction's replace method is not what you need in this case. You will have to switch to
t.add(R.id.content_frame, newFragment, TAG)
With TAG being the tag (a string) of your fragment. In your example you are dealing with 2 fragments so you should define :
private final String TAG_FRAGMENT1 = "fragment1";
private final String TAG_FRAGMENT2 = "fragment2";
And depending of the fragment you want to add, you will call either :
t.add(R.id.content_frame, newFragment, TAG_FRAGMENT1);
OR
t.add(R.id.content_frame, newFragment, TAG_FRAGMENT2);
Followed by :
t.commit();
2/ Now that you will have fragments with TAGs, you will be able to find the existing instance of framgnent1 in the fragment backtrack with :
getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT1);
This will return the instance of fragment1 if it exists or "null" and in this case, you will have to create a new instance and "add" it with a fragmentTransaction (with what I explained in 1/)
3/ If the findFragmentByTag is returning a fragment (and not null) then you should use the replace method :
FragmentManager fm = getSupportFragmentManager();
Fragment f = fm.findFragmentByTag(TAG_FRAGMENT1);
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, f);
ft.commit();
Answered By - poulpi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.