[英]How to go from one fragment to another fragment in kotlin?
我在片段 A 中有一個按鈕,當我單擊片段 A 時,我希望它被重定向到片段 B。如何在 kotlin 中實現這一點? 現在我正在使用此代碼,但應用程序崩潰。
btntest.setOnClickListener {
var intent = Intent(view.context, FragmentB::class.java)
startActivity(intent)
}
我建議你看看導航組件。 首先,您創建一個 Navigation 資源文件(通常稱為 Nav Graph),在其中添加您希望連接的片段。 確保為每個片段提供一個 ID(稍后您將使用它在它們之間導航)。 此外,您可以使用
app:startDestination
來設置要顯示的第一個片段。
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
app:startDestination="@id/blankFragment">
<fragment
android:id="@+id/blankFragment"
android:name="com.example.cashdog.cashdog.BlankFragment"
android:label="@string/label_blank"
tools:layout="@layout/fragment_blank" />
</navigation>
然后,在將托管片段的活動/片段中,添加一個FragmentContainerView
並將圖表設置為您創建的圖表。
<?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=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
最后,為了在 Fragment 之間導航,在托管導航的 Activity 中使用它(如果 Fragment 托管導航,則使用getActivity()
)。
// as per defined in your FragmentContainerView
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
// Navigate using the IDs you defined in your Nav Graph
navController.navigate(R.id.blankFragment)
來源: https://developer.android.com/guide/navigation/navigation-getting-started
編輯:如果要訪問Fragment
中的 controller ,請使用activity?.supportFragmentManager
獲取片段管理器。
在導航圖 xml 中設置操作后,在 From Fragment 中嘗試此操作。
findNavController().navigate(R.id.action_from_fragmentA_to_fragmentB)
在適配器點擊列表器中設置
加載片段(設置片段())
private fun loadFragment(homeFragment: SettingFragment) {
val transaction = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
transaction.replace(R.id.container,homeFragment)
transaction.addToBackStack(null)
transaction.commit()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.