android - Properly replacing Fragments -
i'm wondering proper way change fragments, add them backstack, , restore visibile fragment after screen rotation.
currently, use method initialize first fragment:
private void inflateinitialfragment() { fragmentmanager manager = getfragmentmanager(); fragment mainfragment = manager.findfragmentbytag(mainmenufragment.class.getsimplename()); fragmenttransaction ft = manager.begintransaction(); if (mainfragment == null) { ft.replace(r.id.maincontainer, new mainmenufragment(), mainmenufragment.class.getsimplename()); } else if (!(mainfragment.isadded() && !mainfragment.isdetached() && !mainfragment.isremoving())) { ft.replace(r.id.maincontainer, mainfragment, mainmenufragment.class.getsimplename()); } ft.commit(); manager.executependingtransactions(); }
and display new fragments have methods one:
public void openawards() { getfragmentmanager().begintransaction().replace(r.id.maincontainer, new awardsfragment(), awardsfragment.class.getsimplename()).addtobackstack(null).commit(); }
and go main screen:
@override public void onbackpressed() { if (getfragmentmanager().getbackstackentrycount() == 0) { super.onbackpressed(); } else { getfragmentmanager().popbackstack(); } }
after few screen rotations, i've got crashes one:
java.lang.illegalstateexception: fragment added: mainmenufragment{42c64d90 #0 id=0x7f0b003f mainmenufragment}
how should change visible fragments , restore them after screen rotation?
don't think saving string or fragment each time solution restore them.
if activity extends android.app.activity don't need override onbackpressed(). pop fragments stack automatically.
Comments
Post a Comment