onBackPressed使用NavigationDrawer在片段中关闭应用程序

时间:2015-06-02 14:24:49

标签: android android-fragments android-activity navigation-drawer

我正在使用带有一些片段的NavigationDrawer,问题是当我在一个片段并点击后退按钮时,它会关闭应用程序,然后我必须再次打开它,再次输入我的用户名和密码要使用该应用程序,我该如何防止这种情况发生?

public class NavigationMain extends ActionBarActivity {

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
           //...
}
 public void setFragmentList(int posicao) {

        Fragment fragment = null;

        switch (posicao) {

            case 0:
                fragment = new MainFragment();
                break;
            case 1:
                fragment = new MensagensFragment();
                break;
            case 2:
                fragment = new EscolasFragment();
                break;
            case 3:
                fragment = new AutorizadasFragment();
                break;
            case 4:
                fragment = new CadastroFragment();
                break;

            default:
                break;

        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
            // update selected item and title, then close the drawer
            navigationAdapter.resetarCheck();
            navigationAdapter.setChecked(posicao, true);
            layoutDrawer.closeDrawer(linearDrawer);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }


    }
}

 @Override
    public void onBackPressed() {

        int count = getFragmentManager().getBackStackEntryCount();

        if (count == 0) {
            super.onBackPressed();
            //additional code
        } else {
            getFragmentManager().popBackStack();
        }

    }

1 个答案:

答案 0 :(得分:1)

我认为您错过了在后台堆栈中添加片段事务。请尝试以下方法:

fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();