Android app closes when back button pressed

南楼画角 提交于 2019-12-13 00:14:08

问题


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?


回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/22101442/android-app-closes-when-back-button-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!