我尝试使用以下代码从活动中打开片段:
var cartFragment: CartFragment = CartFragment()
supportFragmentManager.beginTransaction().add(R.id.container, cartFragment)
.commit()
但它产生了错误:没有为片段 CartFragment 的 id 容器找到视图
CartFragment 在dashboard.xml 中使用底部导航菜单调用,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main.Dashboard">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/navigationView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
style="@style/ThemeOverlay.App.BottomNavigationView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:itemBackground="@color/Correct"
app:itemIconTint="@drawable/bottom_navigation_selector"
app:itemTextColor="@color/White"
app:menu="@menu/navigation"/>
</androidx.constraintlayout.widget.ConstraintLayout>
从底部导航调用如下:
R.id.navigation_cart -> {
toolbar.title = "Cart"
val cartFragments = CartFragment.newInstance()
openFragment(cartFragments)
return@OnNavigationItemSelectedListener true
}
cartfragment.xml 中的 cartfragment id 是 cartfragment。当我将 id 更改为 cartfragment 时,它有同样的错误:No view found for id cartfragment for fragment CartFragment 如何纠正这个问题?