关于空对象引用的android.support.v4.app.Fragment.mFragmentManager'

时间:2016-04-21 20:26:47

标签: android android-fragments navigationview

我有以下代码行,我用来创建一个导航视图来加载片段和这个Android应用程序。我收到错误: android.support.v4.app.Fragment.mFragmentManager'对空对象引用。我已经创建了片段,导航视图也可以工作。

public void selectDrawerItem(MenuItem menuItem){

    Fragment fragment = null;
    Class fragmentClass = null;

    switch(menuItem.getItemId()){
        case R.id.nav_show_all_events_activity:
            fragmentClass = AllEventsFragment.class;
            break;
        case R.id.nav_whats_hot_today_activity:
            fragmentClass = WhatsHotFragment.class;
            break;
    }

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

    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();

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

2 个答案:

答案 0 :(得分:0)

您确定菜单中只有2个MenuItems吗?如果还有更多,您最终会得到一个null片段。您可以添加'默认' case switch to switch语句:

switch(menuItem.getItemId()){
    case R.id.nav_show_all_events_activity:
        fragmentClass = AllEventsFragment.class;
        break;
    case R.id.nav_whats_hot_today_activity:
        fragmentClass = WhatsHotFragment.class;
        break;
    default:
        return;
}

这应该确保片段不会为空。

答案 1 :(得分:0)

I analysed the code and wondered why the previous method did not work. I found a minor issue regarding the imports i used. I used the following import android.support.v4.app.Fragment; import in main_activity. Saw that i was using import android.app.Fragment; in the classes AllEventsFragment and WhatsHotFragment, of which i changed the imports to import android.support.v4.app.Fragment; Thank you for your help. Final version below:

public void selectDrawerItem(MenuItem menuItem){

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    Fragment fragment;

    switch(menuItem.getItemId()){
        case R.id.nav_show_all_events_activity:
            fragment = new AllEventsFragment();
            break;
        case R.id.nav_whats_hot_today_activity:
            fragment = new WhatsHotFragment();
            break;
        default:
            return;
    }

    transaction.replace(R.id.flContent, fragment);
    transaction.commit();

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