OnBackPressed不跟随backstack;直接进入家庭片段

时间:2018-04-22 16:48:12

标签: java android android-fragments onbackpressed

我在泡菜中,无法理解发生了什么。我的应用程序使用OnBackPressed关闭窗口和主屏幕检查,简而言之“如果在家,否则,请使用退出菜单”

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else if (!viewIsAtHome) {
        displayView(R.id.nav_large_monsters);
    } else {
        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Home.this.finish();
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }
}

我不想发生的事情是紧逼让我直接回到我的“大怪兽”片段。我希望这能跟随后台。

我在“大怪物”页面上有大约30个按钮,可以将您带入怪物的信息,但是立即按下会显示“你确定要退出”菜单,而不是回到大怪物片段:< / p>

Large Monsters

Pressing Back button from a Monster fragment

显然,它并没有跟随后台。与任何其他屏幕相同,如果我去任何其他片段,它会直接回到Nav_Large_Monsters而不是跟随后台。

我假设我的问题是:

    } else if (!viewIsAtHome) {
        displayView(R.id.nav_large_monsters);

但如果我删除它,应用程序将立即要求退出,而不是回家,仍然没有跟随后台。

如果我将onBackPressed返回到其默认代码,它将跟随backstack,但它不会加载一个主片段并以空白片段开头。

尝试:

  • 我试图删除onBackPressed中的“else if(!viewIsAtHome)”部分,并在我的onNavigationItemSelected方法中实现“default”

    default:
    fragment = new Large_Monsters();
    break;
    

这也行不通。不加载主片段。

  • 以前我有一个showHome()方法,这个DID可以使用backStack并使用一个home片段,但在将我的Fragments更改为v4.support.app.Fragment后,我不得不改变我的Home Activity如何处理我的onNavigationItemSelected。它不喜欢我的showHome方法并且一直在调用我使用旧的FragmentManager而不是v4.support.app.FragmentManager(此方法导致我的应用在更改为v4后立即崩溃):< / p>

    private void showHome() {
    fragment = new Large_Monsters();
    if (fragment != null) {
        android.app.FragmentManager fragMgmt = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
    }
    

    }

  • 我还尝试添加一个关于弹出backStack的If语句,这似乎没有做任何有用的事情:

    if (!fragment.getFragmentManager().popBackStackImmediate()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            finishAfterTransition();
        }
    }
    
  • 我还尝试添加一个If语句,检查Backstack是否为&gt; 0但是这也没有帮助,虽然我删除了那个字符串并且不确定我在哪里找到它。也许我错误地构建了这个字符串。

任何帮助都会很棒!谢谢!

代码:

Home.java(MainActivity,我刚在这个项目中将其命名为Home)

public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
private Fragment fragment = null;
private FragmentManager fragmentManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DatabaseHelper myDbHelper = new DatabaseHelper(Home.this);


    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setItemIconTintList(null);
//        showHome();

    displayView(R.id.nav_large_monsters);

}

private boolean viewIsAtHome;

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else if (!viewIsAtHome) {
        displayView(R.id.nav_large_monsters);
    } else {
        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Home.this.finish();
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.search_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    return super.onOptionsItemSelected(item);
}

//    private void showHome() {
//        fragment = new Large_Monsters();
//        if (fragment != null) {
//            android.app.FragmentManager fragMgmt = getFragmentManager();
//            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
//        }
//    }


@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    displayView(item.getItemId());
    return true;

}

public void displayView(int viewId) {

    Fragment fragment = null;
    String title = getString(R.string.app_name);

    switch (viewId) {
        case R.id.nav_large_monsters:
            fragment = new Large_Monsters();
            title  = "Large Monsters";
            viewIsAtHome = true;
            break;

        case R.id.nav_small_monsters:
            fragment = new Small_Monsters();
            title = "Small Monsters";
            viewIsAtHome = false;
            break;

        case R.id.nav_weapons:
            fragment = new Weapons();
            title = "Weapons";
            viewIsAtHome = false;
            break;

        case R.id.nav_armors:
            fragment = new Armors_Low_High();
            title = "Armor Sets";
            viewIsAtHome = false;
            break;

        case R.id.nav_charms:
            fragment = new Charms();
            title = "Charms";
            viewIsAtHome = false;
            break;

        case R.id.nav_items:
            fragment = new Items();
            title = "Items";
            viewIsAtHome = false;
            break;

        case R.id.palico_armor:
            fragment = new Palico_Armor();
            title = "Palico Armor";
            viewIsAtHome = false;
            break;

        case R.id.palico_gadgets:
            fragment = new Palico_Gadgets();
            title = "Palico Gadgets";
            viewIsAtHome = false;
            break;

        case R.id.palico_weps:
            fragment = new Palico_Weapons();
            title = "Palico Weapons";
            viewIsAtHome = false;
            break;

        case R.id.palico_helms:
            fragment = new Palico_Helms();
            title = "Palico Helmets";
            viewIsAtHome = false;
            break;

        default:
            fragment = new Large_Monsters();
            break;

    }

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame, fragment, fragment.getTag())
                .addToBackStack(null);
                ft.commit();
    }

    // set the toolbar title
    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle(title);
    }

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

}

}

1 个答案:

答案 0 :(得分:1)

如果你要覆盖onBackPressed,你必须自己处理后退的撤消。这就是FragmentActivity的作用:

/**
 * Take care of popping the fragment back stack or finishing the activity
 * as appropriate.
 */
@Override
public void onBackPressed() {
    FragmentManager fragmentManager = mFragments.getSupportFragmentManager();
    final boolean isStateSaved = fragmentManager.isStateSaved();
    if (isStateSaved && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
        // Older versions will throw an exception from the framework
        // FragmentManager.popBackStackImmediate(), so we'll just
        // return here. The Activity is likely already on its way out
        // since the fragmentManager has already been saved.
        return;
    }
    if (isStateSaved || !fragmentManager.popBackStackImmediate()) {
        super.onBackPressed();
    }
}

如果你跳过它,你就不会得到片段弹出行为。所以只需更新你的onBackPressed以包含一个片段管理器的弹出窗口 - 如果成功,你可以提前返回,因为系统会根据需要弹出片段。

@Override
public void onBackPressed() {
    // Pressing back popped the back stack, nothing else to do
    FragmentManager fragmentManager = getSupportFragmentManager();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else if (!fragmentManager.isStateSaved() && fragmentManager.popBackStackImmediate()) {
        return;
    } else {
        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Home.this.finish();
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }
}

<强>更新

您还需要更新displayView方法,因为现在它始终推送堆栈上的内容。所以你的家庭&#34;片段实际上是堆栈中的第一件事,并会弹出让你留下一个空白屏幕。所以,如果你正在展示&#34; home&#34;片段,在片段管理器上调用addToBackStack

此外,您不需要明确设置&#34; home&#34;按下后面的片段,因为弹出后台堆栈应该做正确的事情(参见上面的更新示例)。

希望有所帮助!