Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle backPress with Fragment

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 in Fragment 1 open new Fragment 4.

i want handle back key press event how can i do this on Fragment 4?after clicking back key in Fragment 4 i want to go back Fragment 1.

enter image description here

like image 732
hash Avatar asked Dec 31 '14 06:12

hash


2 Answers

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(); 
    }
}
like image 114
sandeepmaaram Avatar answered Oct 02 '22 23:10

sandeepmaaram


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.
 }
}
like image 45
Bhawna Raheja Avatar answered Oct 02 '22 21:10

Bhawna Raheja