从导航抽屉导航到Mainactivity

时间:2015-11-19 09:06:12

标签: android navigation-drawer

我希望有一种方法可以在切换片段时从导航回到MainActivity。我之前尝试这样做的方式导致应用程序崩溃。主屏幕是主要活动。

public void selectDrawerItem(MenuItem menuItem)
{
    Fragment fragment = null;

    Class fragmentClass;

    switch (menuItem.getItemId())
    {
        case R.id.nav_inspi:
            fragmentClass = InFragment.class;
            break;

        default:
            fragmentClass = InFragment.class;
            break;
    }

    try
    {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e)
    {
        e.printStackTrace();
    }

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.fLayout_, fragment).commit();

    menuItem.setChecked(true);
    setTitle(menuItem.getTitle());
    zDrawerLayout.closeDrawers();
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId())
    {
        case android.R.id.home:
            zDrawerLayout.openDrawer(GravityCompat.START);
            return true;
    }
    if (zDrawerToggle.onOptionsItemSelected(item))
    {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

1 个答案:

答案 0 :(得分:0)

在代码中尝试此更改

 FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.fLayout_, fragment).addToBackStack(null).commit();