The main activity opens the main_fragment with this transaction:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.fragment_main_container, new MainFragment())
.commit();
}
Then I replace that fragment with another one like this:
// method to handle Conversions button click
public void addConversionsFragment (View v) {
// replace the main fragment with the conversion fragment
UnitConversionFragment newFragment = new UnitConversionFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
transaction.replace(R.id.fragment_main_container, newFragment);
// and add the transaction to the back stack so the user can navigate back
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
Originally, I was using support.v4.app.fragment
, and everything was working as expected (back button in the second fragment would pop that one out and return to the MainFragment
. But then I decided to implement a PreferenceFragment
elsewhere, which the support library didn't seem to like. So I converted the whole project to the regular app.fragment
by deleting all the support imports, replacing with the regular imports, then editing all the getSupportFragmentManager()
with getFragmentManager()
, etc.
Good news is thePreferenceFragment
works well, however any time I hit the back button in a fragment, it closes the hosting activity rather than reversing the transaction.
I did many searches and it seems that I am implementing the code correctly, but it is just not responding as I am expecting. Is there more involved in converting away from the support library? Or am I missing something else obvious? I saw a lot of answers out there overriding the onBackPressed()
, but I really don't want to do that.
Is there some fundamental difference between the v4 support library and the regular library that requires me to handle the fragment transactions differently?