如何在不覆盖 activity 的情况下创建片段?

How can I create a fragment without overwrite on top of my activity?

我改了this navigation drawer library as mikepenz's material drawer library。因为当我导入要使用的库时,第一个库出错。但在第一个图书馆,我正在处理导航抽屉项目,点击如下:

 case 2 :

     FragmentManager mFragmentManager = getSupportFragmentManager();
     Fragment mFragment = new PM_Fragment().newInstance(mHelpLiveo.get(position).getName());

     if (mFragment != null){
         mFragmentManager.beginTransaction().replace(R.id.container, mFragment).commit();
     }

     break;

对于我的第二个库,我遇到了 "R.id.container couldn't found" 错误。我猜容器 ID 是在库内部创建的。由于这个原因,我试图用一个 id 来替换。所以我把我的 activity_main 布局的第一个 id 放在下面:

case 2:
    mFragmentManager = getSupportFragmentManager();
    mFragment = new PM_Fragment().newInstance(String.valueOf(position));

    if (mFragment != null) {
        mFragmentManager.beginTransaction().replace(R.id.content_frame, mFragment).commit();
    }

    break;

我的 R.id.content_frame 来自我的 activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<include
    android:id="@+id/toolbar1"
    layout="@layout/toolbar"/>

<TextView
    android:id="@+id/helloid"
    android:text="@string/hello_world" android:layout_width="wrap_content"
    android:layout_below="@id/toolbar1"
    android:layout_height="wrap_content"
    android:textSize="25dp"/>...

但是当我单击一个项目时,新片段会写在我的 activity_main.xml 布局之上。这是我的截图 :D

如有任何帮助,我们将不胜感激。

我想问题之一是您在相对布局中插入片段,而框架布局更合适;我建议您使用 Google 提供的导航视图和抽屉布局 Android 小部件而不是第三方库,如果您需要有关导航视图和具体使用方法请告诉我或者参考官方文档

这是一个 link 到 google 的开发者页面:

http://developer.android.com/reference/android/support/design/widget/NavigationView.html

content_frame 是您的主要 activity 布局的 id 这就是它发生的原因 使用新的相对布局并给它 id content_frame