Android:如何将片段加载到FrameLayout中
我从Android开始,在我的项目中我正在使用这个BottomBar 。 喜欢它,效果很好。 我的应用程序的代码与他在教程中使用的代码几乎完全相同,唯一不同的是我的MainActivity
从AppCompatActivity
扩展。
现在我要做的是在FrameLayout
加载片段:
为此,我正在尝试这段代码,我发现谷歌搜索我的问题的答案:
// 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
。 我的QrCode类: public class QrCodeFragment extends Fragment
当我今天开始使用Android时,如果我做的正确,我会感到困惑。 如果我真的应该在FrameLayout
加载片段,如果是的话,我做错了什么我无法加载它 。 我知道这是我片段的类型,但我不知道如何使用所需类型创建它。 我使用Android Studio > New > Fragment > Fragment (Blank)
创建了它
谢谢你的帮助
更新:我在这篇文章中找到了我的错误的解决方案,但即使没有错误,我仍然看不到片段。
首先,你的Fragment交易行中有一个错误,根据你的布局应该是:
transaction.replace(R.id.contentContainer, newFragment); // not R.id.bottomBar
其次,您应该使用supportFragmentManager而不是fragmentManager来处理支持片段,因此请执行以下方法:
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.contentContainer, newFragment); transaction.addToBackStack(null); transaction.commit();