How to Handle backPress with Fragment

前端 未结 3 668
无人及你
无人及你 2020-12-01 22:24

i have Fragment Activity With contatin navigation drawer.after clicking navigation drawer item it open a Fragment 1, fragment 2, Fragment 3.and then after button click event

相关标签:
3条回答
  • 2020-12-01 22:44

    Override onBackPress() method and check that your fragement manager has backStack entry>0 if it has greater than 0 than do popback stack otherwise finish your activity..

    if(getFramentManager().getBackStackEntryCount()>0){
          // popback statck.
    }
     else{
         // finish your activity.
     }
    

    don't forget to add your fragement to BackStack to maintain fragment hierarchy..

    fragTransacion.addToBackStack(TAG);
    
    0 讨论(0)
  • 2020-12-01 22:45

    Your code for adding fragment to backstack should be like:

    getFragmentManager() .beginTransaction() .replace(R.id.content_frame, Entry_Account.newInstance(), Entry_Account.TAG).addToBackStack("Some string") .commit();
    

    Then On Activity's onBackPressed method,use this snippet:

    @Override
    public void onBackPressed () {
    if(getFramentManager().getBackStackEntryCount()>0){
          // popback statck.
    }
     else{
         // finish your activity.
     }
    }
    
    0 讨论(0)
  • 2020-12-01 23:05

    Add Fragments To BackStack. Before commit() the transaction, use addToBackStack() method i.e

     addToBackStack("Some String").commit();
    

    and in onBackPressed()

    @Override 
    public void onBackPressed() { 
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack(); 
        } else { 
            this.finish(); 
        }
    }
    
    0 讨论(0)
提交回复
热议问题