android - Manage fragment life cycle with navigation drawer -
i have architectural issue in application . have used 1 activity navigation drawer , several fragments .now ,
suppose have 2 fragments , b . navigation structure somewhat:
a
a1 a2
b
b1 b2
where a1,a2 of type fragment , b1,b2 of type b fragment. difference between same type of fragments eg. a1,a2 of data .
my first approach :
whenever user click on a1,a2,b1,b2 . create new instance of type , replace fragment.
fragment fragment =a.newinstance(); private void replacefragment(fragment fragment) { fragmentmanager fragmentmanager = getsupportfragmentmanager(); fragmentmanager.begintransaction() .replace(r.id.content_frame, fragment).commit(); mdrawerlayout.closedrawer(rldrawer); }
note : not want add them stack.
later on realize approach inefficient every time crate new instance on fragment if of same type . said before difference in data .so, move next approach
second approach :
now activity has data member (references) of fragment , b . check if null create new instance else change data :
if (a == null) { = a.newinstance(); } else { ((a) a).changedata(); } replacefragment(a);
problem approach when switch fragment a1 b1 a1 fragment destroyed reference remain activity . when switch b1 a1 not create new instance can see in above code @ same time oncreate() method gets called on fragment a.
should remove reference activity ondestroy() called on fragment ?
does second approach correct ?
is there better approach this?
thanks in advance.
i modify first approach.
use string tags fragment. when replacing fragment use replace
method 3 parameters, example:
fragmentmanager.begintransaction() .replace(r.id.content_frame, fragment, tag_a1).commit();
where tag_a1
unique string tag.
you can use method findfragmentbytag fragmentmanager check if fragment created before replace.
fragmentmanager fragmentmanager = getsupportfragmentmanager(); fragment fragmenta1 = fragmentmanager.findfragmentbytag(tag_a1); if(fragment == null) { fragment = a.newinstance(); } fragmentmanager.begintransaction() .replace(r.id.content_frame, fragment, tag_a1).commit();
Comments
Post a Comment