导航抽屉带有活动而不是碎片

时间:2014-07-14 08:52:00

标签: android android-fragments navigation-drawer

我所拥有的是左导航菜单,我使用导航抽屉,它与碎片一起工作得很好,我有五个按钮,每个打开一个片段,但现在我希望每个案例打开一个活动,而不是片段,和我试图使用意图但它没有用!! 这是我的代码:

private void displayView(int position) {
        // update the main content by replacing fragments
        android.app.Fragment fragment = null;
        switch (position) {
        case 0:
            //fragment = new HomeFragment();
//          Intent i=new Intent(MainActivity.this,MainActivity.class);
//          startActivity(i);
            break;
        case 1:
            //fragment = new FindPeopleFragment();
            break;
        case 2:
            //fragment = new PhotosFragment();
            break;
        case 3:
            //fragment = new CommunityFragment();
            break;
        case 4:
            //fragment = new PagesFragment();
            break;
        case 5:
            //fragment = new WhatsHotFragment();
            break;

        default:
            break;
        }

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

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

那么我应该在这段代码中改变什么,以便它可以打开一个活动而不是片段?有谁可以帮助我?

2 个答案:

答案 0 :(得分:0)

在某些情况下,您需要更改函数以加载类Fragment,在其他情况下,需要更改类Activity

case 0:
activity = new MyActivity();
fragment = null;
break;
case 1:
fragment = new MyFragment();
activity = null;
break;  

if (fragment != null) {
  FragmentManager fragmentManager = getFragmentManager();
  fragmentManager.beginTransaction().replace(R.id.frame_container, (android.app.Fragment) fragment).commit();
  setTitle(menutitles[position]);
  mDrawerLayout.closeDrawer(mDrawerList);
}else {
  if(activity != null) {
     Intent i1 = new Intent(MainActivity.this, activity.getClass());
     i1.putExtra(EXTRA_MESSAGE, position);
     startActivity(i1);  
     setTitle(menutitles[position]);
     mDrawerLayout.closeDrawer(mDrawerList);
  }
}

答案 1 :(得分:0)

请你从Logcat发布错误:

我首先要检查的是:

  • Manifest.xml中的活动是否为Activies?
  • 然后检查您是否使用Intent调用Activities,而不是Fragments

这是您正确启动活动的方式。

Intent intent = new Intent(mActivity, class1); // class1 The class to open
startActivity(intent);