android - Popbackstack Finishes Activity in OnBackPressed -
i have activity 2 fragments (list & details), in oncreate(), start list fragment if savedinstance null so
public static final int client_list_fragment = 1; public static final int client_details_fragment = 2; private int currentfragment = 0; if (savedinstancestate == null) { //on first run, start list fragment if (currentfragment == 0) { clientlistfragment listfrag = new clientlistfragment(); getsupportfragmentmanager().begintransaction() .add(r.id.container_client, listfrag, constants.client_list_fragment_tag) .commit(); currentfragment = client_list_fragment; } else { switch (currentfragment) { case client_list_fragment: addlistfragment(); break; case client_details_fragment: adddetailsfragment(0); break; } } }
and here method add detailsfragment , listfragment needed
private void addlistfragment(){ clientdetailsfragment listfrag = new clientdetailsfragment(); getsupportfragmentmanager().begintransaction() .replace(r.id.container_client, listfrag, constants.client_list_fragment_tag) .addtobackstack("details") .commit(); currentfragment = client_list_fragment; } private void adddetailsfragment(long companyid){ clientdetailsfragment detailsfrag = clientdetailsfragment.newinstance(companyid); getsupportfragmentmanager().begintransaction() .replace(r.id.container_client, detailsfrag, constants.client_details_tag) .addtobackstack(null) .commit(); currentfragment = client_details_fragment; }
this works expected except when click button details fragment, instead of taking me list fragment, finishes activity. goes list fragment split second , finishes host activity , goes calling activity. how can stop behavior, after going through lot of onbackpress related question on here overide of onbackpressed
@override public void onbackpressed() { if (currentfragment == client_details_fragment){ getsupportfragmentmanager().popbackstackimmediate(); }else { super.onbackpressed(); } }
thanks
i check whether current fragment instance belongs fragment invoked onbackpressed(). code untested; it's give idea on how proceed. hope not calling this.finish() on activity
.
@override public void onbackpressed() { fragment fragment = getsuportfragmentmanager().findfragmentbytag(constants.client_details_tag); if (fragment instanceof clientdetailsfragment) { getsupportfragmentmanager().popbackstackimmediate(); } else { super.onbackpressed(); } }
let me know if helps.
Comments
Post a Comment