Search code examples
androidfragmentback-stack

Fragment addToBackStack closing App


I didnt find any solution for my problem.

I got several Fragments (dynamically created), but my Back Button is not working at all, pressing it will close the App, whatever fragment is "active".

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {

case R.id.itemAdd:
FragmentTransaction tx = getFragmentManager().beginTransaction();
    Fragment fragment = new NeuesProduktFrag();

    tx.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right,
             R.anim.slide_in_left, R.anim.slide_out_right);
     tx.replace(R.id.main, fragment);
     tx.addToBackStack(null);
     tx.commit();
    return true;

Everything works fine, but after entering "NeuesProduktFrag" Fragment and pressing Back-Button my App closes. Tried it in different Buttons etc. Overriding onBackPressed is not needed right ? addToBackStack should do the trick or not ?


Solution

  • After i struggeled a long time, this is my final Code:

    @Override
    public void onBackPressed() {
    
    // initialize variables
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    
    // check to see if stack is empty
    if (fm.getBackStackEntryCount() > 0) {          
        fm.popBackStack();
        ft.commit();    
    }
    else {
        if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
    Toast.makeText(this, "Nochmal drücken zum Beenden!", 4000).show();
    this.lastBackPressTime = System.currentTimeMillis();
    } else{
            super.onBackPressed();
        }        
    }
    }
    

    I used it in my FragmentActivity and added a double tab to close the App finally.