Android:如何将片段加载到FrameLayout中

And*_*uiz 4 java android android-fragments

我从Android开始,在我的项目中我正在使用这个BottomBar.喜欢它,效果很好.我的应用程序的代码几乎与他在教程中使用的代码完全相同,唯一不同的是我的MainActivity延伸AppCompatActivity.

现在我要做的是在以下内容中加载片段FrameLayout:

<!-- This could be your fragment container, or something -->
<FrameLayout
    android:id="@+id/contentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/bottomBar"
    />
Run Code Online (Sandbox Code Playgroud)

为此,我正在尝试这段代码,我发现谷歌搜索我的问题的答案:

// Create new fragment and transaction
QrCodeFragment newFragment = new QrCodeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.bottomBar, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();
Run Code Online (Sandbox Code Playgroud)

该行transaction.replace(R.id.bottomBar, newFragment);抱怨newFragment的类型,应该是android.app.Fragment.我的QrCode类:public class QrCodeFragment extends Fragment

当我今天开始使用Android时,如果我做对了,我会感到困惑.如果我真的应该在里面加载片段FrameLayout,如果是的话,我做错了什么我无法加载它.我知道这是我的片段的类型,但我不知道如何使用所需类型创建它.我是用它创建的Android Studio > New > Fragment > Fragment (Blank)

谢谢你的帮助


更新:我在这篇文章中找到了我的错误的解决方案,但即使没有错误,我仍然看不到片段.

Ale*_*xTa 10

首先,你的Fragment交易行中有一个错误,根据你的布局应该是:

transaction.replace(R.id.contentContainer, newFragment); // not R.id.bottomBar
Run Code Online (Sandbox Code Playgroud)

其次,您应该使用supportFragmentManager而不是fragmentManager来处理支持片段,因此请执行以下方法:

final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.contentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Run Code Online (Sandbox Code Playgroud)