使用后退按钮从片段返回主要活动

时间:2017-02-23 12:59:50

标签: android android-layout android-fragments

您好我已经在app抽屉中创建了片段,现在当我按下片段上的后退按钮时,它正在关闭应用程序。

主要活动的webView中已经存在一个onKeyDown。

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (myWebView.canGoBack()) {
                    myWebView.goBack();
                } else {
                    finish();
                }
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);

对于onBackPressed方法

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }

Fragment Impementation方法,

if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_main, fragment);
        ft.addToBackStack("close");
        ft.commit();




    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

3 个答案:

答案 0 :(得分:1)

当您将片段添加到某个容器或使用xml对其进行充气时,它不会添加到Backstack中,因此,当' onBackPressed'它会从backstack抛出最后一个活动 - 这是托管片段的活动,从而退出应用程序。 我想这篇文章: Android: Fragments backStack

可以帮助您,它解释了如何将片段事务添加到backstack:

FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(..............);
    fragmentTransaction.addToBackStack("fragment transaction name, not required");
    fragmentTransaction.commit(); 

答案 1 :(得分:1)

您需要按照以下方式执行此操作

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
            //that means your stack is empty and you want to close activity
            finish();
        } else {
            // pop the backstack here
            getSupportFragmentManager().popBackStackImmediate();
        }
    }

}

答案 2 :(得分:0)

当你唤起一个片段时,将它添加到堆栈中,就像这样

fragmentTransaction.addToBackStack("fragment");

然后在onBackPress中像这样从堆栈中弹出它

FragmentManager fm = getActivity()
                .getSupportFragmentManager();
        fm.popBackStack ("fragment", FragmentManager.POP_BACK_STACK_INCLUSIVE);