java - Navigation drawer back button to primary fragment -


after reading this , searching in android documentation, gave , decided ask here. i'm trying set button in navigation drawer app close home fragment, , other fragment take home. example, if begin @ home fragment , navigate other fragments in navigation drawer, when hit button home fragment, , if hit home fragment, exit app.

i have tried implement this:

public void onnavigationdraweritemselected(int position) {        ...     // if next fragment home, clear backstack.     if (frag instanceof home) {         getsupportfragmentmanager().popbackstack();         fragmentmanager.begintransaction().replace(r.id.container, frag)                 .commit();     }     // if backstack contains transaction, replace current fragment     else if (getsupportfragmentmanager().getbackstackentrycount() > 0) {         fragmentmanager.begintransaction().replace(r.id.container, frag)                 .commit();     }      // if backstack empty, insert home -> fragment transaction     else {         fragmentmanager.begintransaction().replace(r.id.container, frag)                 .addtobackstack("").commit();     }     ... }      ...  @override public void onbackpressed() {      if (drawerlayout.isdraweropen(gravity.start)) {         drawerlayout.closedrawer(gravity.left);     } else {         super.onbackpressed();         // if returning home fragment, restore action bar title.         if (getsupportfragmentmanager().getbackstackentrycount() > 0)             onsectionattached(0);     } } 

the link have attached not working properly, , way implemented not working consistently. example, if navigate home other fragments , home (without pressing button), fragments overlay 1 another.

i found way make work easy, decided post here:

// in home fragment? private boolean homefrag = true; ... @override public void onnavigationdraweritemselected(int position) {     ...     // next fragment home?     if (frag instanceof home)         homefrag = true;     else         homefrag = false;      fragmentmanager.begintransaction().replace(r.id.container, frag)             .commit();     onsectionattached(position); } ... @override public void onbackpressed() {     // close navigation drawer if open     if (drawerlayout.isdraweropen(gravity.start)) {         drawerlayout.closedrawer(gravity.left);     } else {         // if not in home, move home.         if (!homefrag) {             onnavigationdraweritemselected(0);         } else             super.onbackpressed();     } } 

i hear thoughts solution.


Comments