Sunday, 15 March 2015

android - Fragment transactions and fragment creation -



android - Fragment transactions and fragment creation -

i'm having little problem understanding behavior of fragments within activity. consider next scenario: have holder activity , 2 or more fragments inside. oncreate method activity this:

@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_holder); if (savedinstancestate == null) { getfragmentmanager().begintransaction().add(r.id.container, new frag1(), "zzz").commit(); } }

i have button in frag1 linked callback in activity:

@override public void bam(string s) { fragmentmanager fragmentmanager = getfragmentmanager(); fragmenttransaction begintransaction = fragmentmanager.begintransaction(); begintransaction.replace(r.id.container, new frag2()); begintransaction.addtobackstack(null); begintransaction.commit(); }

at point frag2 on stack , visible fragment. used replace , addtobackstack because need navigation. problem when rotate screen while within frag2, super.oncreate(savedinstancestate) method activity calls constructor frag1.

is there way avoid phone call frag1's constructor until user presses button?

fragments added backstack remain in memory , cannnot garbage collected. kept actual references fragments. reason recreated because still have instance of fragment. can still phone call it's methods , fields can other object; it's not visible user , trying manipulate views may fail.

if purpose of adding fragment backstack navigation, can accomplished not putting fragment in backstack beging with, letting instance of fragment fall out of memory, overriding onbackpressed() in activity can re-create() fragment 1. free cache info need well.

the purpose of backstack preserve fragments state. when it's written backstack ondestroyview() called, it's viewhierarchy saved onsaveinstancestate(). saves stuff text in textviews, scroll positions, etc.

if there's resource intensive stuff in fragment 1's initialization can seek moving later lifecycle event, onresume().

android android-fragments

No comments:

Post a Comment