I have the following activity which launches a fragment when the tab is selected:
public class MainActivity extends Activity implements TabListener {
Fragment f = null;
.....
public void onTabSelected(Tab tab, FragmentTransaction ft) {
.....
if (tab.getPosition() == 0) {
if (initalSync == true) {
progress1.setVisibility(TRIM_MEMORY_UI_HIDDEN);
}
f = new EventFragment();
Bundle data = new Bundle();
data.putInt("idx", tab.getPosition());
f.setArguments(data);
}
if (tab.getPosition() == 1) {
progress1.setVisibility(TRIM_MEMORY_UI_HIDDEN);
f = new MapsFragment();
Bundle data = new Bundle();
data.putInt("idx", tab.getPosition());
f.setArguments(data);
}
.....
ft.replace(android.R.id.content, f);
}
When ever I press the phones back button on any of the fragments it closes my app. I know this is related to the backstack but every method I have tried fails.
any ideas?
You need to call addToBackstack(null) on the Transaction to add the fragment to the backstack. Then the back button should revert to the previous fragment.
You need to add your fragments to the backstack if you don't want the activity to close by the time you press back, all you have to do is calling the following method:
before you replace and commit your transaction. This way the fragments injection you are using will be tracked down, and the back button will change to the previos fragment until reaching the first action and then it will close the app.
Regards!