【发布时间】:2017-05-31 18:58:02
【问题描述】:
我从 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"
/>
为此,我正在尝试这段代码,我发现它在谷歌上搜索我的问题的答案:
// 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();
transaction.replace(R.id.bottomBar, newFragment); 这一行在抱怨 newFragment 的类型,应该是 android.app.Fragment。我的二维码课:public class QrCodeFragment extends Fragment
当我今天开始使用 Android 时,我很困惑我是否做对了。 如果我真的应该在FrameLayout 中加载片段,如果是这样,我做错了什么,我无法加载它。我知道这是我的片段的类型,但我不知道如何使用所需的类型创建它。我使用Android Studio > New > Fragment > Fragment (Blank)创建它
感谢您的帮助
更新: 我在this post 中找到了我的错误的解决方案,但即使没有错误我仍然看不到片段。
【问题讨论】:
-
据我了解,容器就是你将片段充气到的东西。这意味着如果你将它膨胀成 FrameLayout,它应该仍然没问题 - 试试看。如果“complain”表示编译错误或crash,你应该指定
-
@LunarWatcher 我实际上发现了这个问题,它不再让我出错了。我应该只导入 android.app.Fragment;而不是导入 android.support.v4.app.Fragment; .现在的问题是它没有显示我刚刚设置显示的片段
标签: java android android-fragments