I'm trying to replace a Fragment with another Fragment dynamically in my activity.
It looks like you can't replace a fragment statically defined in a layout file, with a dynamically created fragment: Android: can't replace one fragment with another
The suggested solution was to add the original Fragment dynamically in the onCreate method:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ShelfFragment shelves = new ShelfFragment();
ft.add(R.id.left_fragment, shelves);
ft.addToBackStack(null);
ft.commit();
}
This works, but when the user presses the back button, the original Fragment is removed instead of closing the Activity because the FragmentTransaction added it to the FragmentManager stack.
Is there a way to add the initial Fragment to my activity without a Transaction/Stack entry?