Android app closes when back button pressed

2019-08-10 12:10发布

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?

2条回答
祖国的老花朵
2楼-- · 2019-08-10 12:31

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.

查看更多
何必那么认真
3楼-- · 2019-08-10 12:54

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:

ft.addToBackStack(null)

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!

查看更多
登录 后发表回答