我在片段 A 中有一個按鈕,當我點擊片段 A 時,我希望它被重定向到片段 B。如何在 kotlin 中實作這一點?現在我正在使用此代碼但應用程式崩潰。
btntest.setOnClickListener {
var intent = Intent(view.context, FragmentB::class.java)
startActivity(intent)
}
uj5u.com熱心網友回復:
我建議你看看
確保為每個片段提供一個 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>
然后,在將托管片段的活動/片段中,添加 aFragmentContainerView并將圖形設定為您創建的圖形。
<?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>
最后,為了在片段之間導航,請在承載導航的 Activity 中使用它(getActivity()如果 Fragment 承載導航,則使用)。
// 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使用activity?.supportFragmentManager獲取片段管理器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369211.html
標籤:安卓 科特林 android-fragments 分段
