如何从活动中打开片段?

问题描述

我尝试使用以下代码打开活动的片段:

var cartFragment: CartFragment = CartFragment()
        supportFragmentManager.beginTransaction().add(R.id.container,cartFragment)
            .commit()

但是它产生了错误: 找不到片段CartFragment的ID容器的视图

CartFragment在仪表板.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时,它具有相同的错误: 找不到片段CartFragment的ID Cartfragment的视图 该如何纠正?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)