【问题标题】:how to open fragment from activity?如何从活动中打开片段?
【发布时间】:2020-08-24 02:51:54
【问题描述】:

我尝试使用此代码从活动中打开片段:

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

但它产生了错误: 未找到片段 CartFragment 的 id 容器的视图

使用dashboard.xml 中的底部导航菜单调用CartFragment,如下所示:

<?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 的视图 如何纠正这个问题?

【问题讨论】:

  • 您提供的 XML 布局代码是 CartFragment 的吗?
  • @Rajeshkumar,xml布局是dashboard xml,所以必须先调用dashboard,然后从dashboard打开fragment

标签: kotlin android-activity navigation fragment bottom


【解决方案1】:

确保在活动类的 onCreate 方法中使用正确的布局资源 ID。我试过你的dashboard.xml,效果很好:

class Dashboard: AppCompatActivity {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dashboard)

        supportFragmentManager
            .beginTransaction()
            .replace(R.id.container, CartFragment.newInstance())
            .commit()
    }
}

这个错误:

java.lang.IllegalArgumentException: No view found for id 0x7f0900c3 (...:id/container) for fragment CartFragment.

仅当您用作活动内容视图的布局实际上没有您尝试使用的 ID 的视图时才会发生。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多