[英]how to open fragment from activity?
我嘗試使用以下代碼從活動中打開片段:
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 時,它有同樣的錯誤:沒有找到片段 CartFragment 的 id cartfragment 的視圖 如何更正?
確保在活動類的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 的視圖時才會發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.