如何在Android Studio导航抽屉中设置默认片段?

时间:2014-07-23 04:58:19

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

我正在寻找一种在我的导航抽屉中找到默认片段的方法,这不是第0项。我已经看到了一些基于检查savedInstanceState是否为null的解决方案但是我觉得我在onNavigationDrawerItemSelected方法中无法访问此内容。这是我的班级:

public class Main extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the Main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new HomeFragment();
            break;
        case 2:
            fragment = new HomeFragment();
            break;
        default:
            fragment = new DiscoverFragment();
    }


    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment).commit();

    }

}

1 个答案:

答案 0 :(得分:7)

答案很简单。由于DrawerLayout让您自己管理片段,因此您可以使用将在普通FragmentActivity中使用的基本FragmentManager API。

我使用以下方法使其更简单,即使当前没有添加到容器中,也会替换当前片段。只需使用您希望在onCreate()方法中默认的片段调用此方法。

public void setFragment(Fragment fragment) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
                   .replace(R.id.container, fragment)
                   .commit();
}

请注意,在第一次调用中使用.add(fragment)而不是.replace在技术上更正确,因为您没有替换任何东西,但它确实无关紧要,因为在内部,它基本上只是删除任何现有片段,并使用.add()为您添加新片段 http://developer.android.com/reference/android/app/FragmentTransaction.html#replace(int,android.app.Fragment,java.lang.String)