[英]Android: how to load fragment into FrameLayout
我从 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
。 我的 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();
在我的情况下,我通过使用解决它
androidx.fragment.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
更换你的
片段事务
bottomNavigationView= findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@SuppressLint("NonConstantResourceId")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment temp =null;
switch (item.getItemId()) {
case R.id.library:
temp = new LibraryFragment();
break;
case R.id.search:
temp = new SearchFragment();
break;
case R.id.profile:
temp = new UserprofileFragment();
break;
default:
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, temp).commit();
return true;
}
});
getSupportFragmentManager().beginTransaction().replace(R.id.fragment,new SearchFragment()).commit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.