Я предполагаю, что вы используете шаблон kotlin
и One Activity , выполните следующие шаги
build.gradle
implementation "androidx.navigation:navigation-fragment-ktx:2.3.0-alpha03"
implementation "androidx.navigation:navigation-ui-ktx:2.3.0-alpha03"
добавить меню в папку res-> menu
main_menu. xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/fragment_two"
android:title="Fragment Two"
/>
</menu>
MainActivity
class MainActivity : AppCompatActivity() {
lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController = findNavController(this, R.id.nav_host_fragment)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
}
}
activity_main. 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/main_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
в res-> навигации mian_graph. xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_graph"
app:startDestination="@id/fragment_one">
<fragment android:id="@+id/fragment_one"
android:label="FragmentOne"
android:name="com.mohammedalaamorsi.test.FragmentOne" />// here you should put the path for your fragment
<fragment android:id="@+id/fragment_two"
android:label="FragmentTwo"
android:name="com.mohammedalaamorsi.test.FragmentTwo" />// here you should put the path for your fragment
</navigation>