Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addToBackStack() not working

I have my MainActivity that manages two fragments working together. One of my methods is a listener interface on my ListFragment and the MainActivity is in charge of switching the fragments.

But for some reason it seems like the addToBackStack doesnt work. When I tap on the list, go to the next fragment and tap the back button of the device...it just goes outside of the App, on the device home screen.

Anyone knows what the issue is?

@Override
public void OnSelectionChanged(Object object) {
    DetailFragment DetailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detail_fragment);

    if (DetailFragment != null) {
        DetailFragment.setTitle(object);
    } else {
        DetailFragment newDetailFragment = new DetailFragment();
        Bundle args = new Bundle();

        args.putSerializable(DetailFragment.KEY_POSITION,object);
        newDetailFragment.setArguments(args);
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();

        fragmentTransaction.replace(R.id.fragment_container, newDetailFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}
like image 616
Makoto Avatar asked Sep 29 '22 22:09

Makoto


1 Answers

You should add this method in your MainActivity.

@Override
public void onBackPressed() {
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        fm.popBackStack();
    } else {
        super.onBackPressed();
    }
}

And check your imports to use android.app. instead of android.support.v4.app.

For example:

import android.app.FragmentManager;

instead of :

import android.support.v4.app.FragmentManager;
like image 182
sevshum Avatar answered Oct 06 '22 02:10

sevshum