I'm using the following activity layout with a fragment and a BottomNavigationView:
<LinearLayout 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="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="#navigation/navigation_bottom"
app:defaultNavHost="true"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottom_navigation_view"
app:menu="#menu/bottom_navigation_menu"/>
</LinearLayout>
And have defined three fragments in my navigation layout:
<navigation
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:id="#+id/navigation_bottom"
app:startDestination="#id/firstFragment">
<fragment
android:id="#+id/firstFragment"
android:name="fragments.FirstFragment"
android:label="fragment_first"
tools:layout="#layout/fragment_first" />
//The other two fragments
</navigation>
Inside my activity, I'm using the following code:
navController = Navigation.findNavController(this, R.id.fragment);
BottomNavigationView bnw = findViewById(R.id.bottom_navigation_view);
NavigationUI.setupWithNavController(bnw, navController);
NavigationUI.setupActionBarWithNavController(this, navController);
And this my onSupportNavigateUp method:
#Override
public boolean onSupportNavigateUp() {
return Navigation.findNavController(this, R.id.fragment).navigateUp();
}
But when I press on the second icon (fragment) nothing happens. How to solve this issue? Thanks!
Solution 1:
In your menu(bottom_navigation_menu) item set same id as your fragment id generated by navigation graph like below:
<menu xmlns:android="http://schemas.android.com. /apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/firstFragment"
android:title="First fragment" />
<item
android:id="#+id/secondFragment"
android:title="Second fragmnet" />
<item
android:id="#+id/thirdFragment"
android:title="Third fragment" />
</menu>
You don't need to set by pro-grammatically because
NavigationUI.setupWithNavController(bnw, navController);
method will do the job.
Solution 2: Not recomended and Un-necessary
But if you want pro-grammatically then do like below:
private lateinit var navController: NavController
private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
navController.navigate(R.id.firstFragment)
return#OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
navController.navigate(R.id.secondFragment)
return#OnNavigationItemSelectedListener true
}
R.id.navigation_notifications -> {
Toast.makeText(this,R.string.title_notifications,Toast.LENGTH_SHORT).show()
navController.navigate(R.id.thirdFragment)
return#OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController = findNavController(R.id.nav_controller_fragment)
navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
}
Related
Take a Bottom Navigation activity from android studio template. there are 3 fragment with 3 item in BottomNavBar (HomeFragment, DashboardFragment, NotificationsFragment) navigate to DashboardFragment from HomeFragment by a button click. after that home item click from BottomNavBar should open Homefragment. But not working as expected.
Go to DashboardFrament from HomeFrament by
textView.setOnClickListener {
findNavController().navigate(R.id.navigation_dashboard)
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_main)
navView.setupWithNavController(navController)
}
}
main_activity.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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment_activity_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
HomeFramgent.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val textView: TextView = view.findViewById(R.id.text_home)
textView.setOnClickListener {
findNavController().navigate(R.id.navigation_dashboard)
}
}
navigation.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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mobile_navigation"
app:startDestination="#+id/navigation_home">
<fragment
android:id="#+id/navigation_home"
android:name="com.app.bottomnav.ui.home.HomeFragment"
android:label="#string/title_home"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/navigation_dashboard"
android:name="com.app.bottomnav.ui.dashboard.DashboardFragment"
android:label="#string/title_dashboard"
tools:layout="#layout/fragment_dashboard" />
<fragment
android:id="#+id/navigation_notifications"
android:name="com.app.bottomnav.ui.notifications.NotificationsFragment"
android:label="#string/title_notifications"
tools:layout="#layout/fragment_notifications" />
</navigation>
Whenever you are navigating to any root destination from another fragment, you should have to clear the previous stack using popUpTo option builder.
Update your code navigation code in your home fragment.
findNavController()
.navigate(R.id.navigation_dashboard,
null,
NavOptions.Builder()
.setPopUpTo(R.id.navigation_home, true)
.build()
)
I don't know what is the best solution for that problem but here is a workaround:
In your activity you add public method:
fun navigateToNavBarDestination(destinationId: Int) {
binding.navView.setSelectedItemId(destinationId)
}
And in your fragments referenced in BottomNavigationView instead calling NavController::navigate you navigate in that way, lets say to dashboard:
fun navigateToDashboard() {
(activity as? MainActivity)?.navigateToNavBarDestination(R.id.dashboard)
}
Its not the perfect solution but works.
Add these lines in your MainActivity onCreate.
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_home,
R.id.navigation_dashboard,
R.id.navigation_notifications
))
setupActionBarWithNavController(navController, appBarConfiguration)
Good morning, any recommendations to use, navigation componets: BottomNavigationView and NavigationDrawer, In a project android.
This project was based on the Samples for Android Architecture Components repository. This is the repository where I took it out:
https://github.com/mackgaru/architecture-components-samples/tree/main/NavigationAdvancedSample
When clicking on a NavigationDrawer item, the navigation does not work well or the app crashes.
This is my repo, if you want to give me a hand:
https://github.com/mackgaru/nBottom_nDrawer.git
Thank you so much.
BottonNavigationView, NavigationDrawer
Here is the error
Process: com.cocktapp.cocktapp, PID: 27899
java.lang.IllegalArgumentException: Navigation action/destination com.cocktapp.cocktapp:id/action_navigation_home_to_homeDetalleFragment cannot be found from the current destination Destination(com.cocktapp.cocktapp:id/homeDetalleFragment) label=Detalle class=com.cocktapp.cocktapp.ui.home.HomeDetalleFragment
at androidx.navigation.NavController.navigate(NavController.java:938)
at androidx.navigation.NavController.navigate(NavController.java:875)
at androidx.navigation.NavController.navigate(NavController.java:861)
at androidx.navigation.NavController.navigate(NavController.java:849)
at com.cocktapp.cocktapp.ui.MainActivity.onNavigationItemSelected(MainActivity.kt:95)
at com.google.android.material.navigation.NavigationView$1.onMenuItemSelected(NavigationView.java:217)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985)
at com.google.android.material.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:416)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
MainActivity
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private var currentNavController: LiveData<NavController>? = null
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
private lateinit var drawerLayout: DrawerLayout
private lateinit var viewModelHome: HomeViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
if (savedInstanceState == null) {
setupBottomNavigationBar()
}
setSupportActionBar(binding.includeMainContent.toolbarActivity)
drawerLayout = binding.drawerLayout
val navigationView: NavigationView = binding.navView
val toogle = ActionBarDrawerToggle(this, drawerLayout, binding.includeMainContent.toolbarActivity, R.string.open_navigation, R.string.close_navigation)
drawerLayout.addDrawerListener(toogle)
toogle.syncState()
navigationView.setNavigationItemSelectedListener(this)
}//fin onCreate
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
setupBottomNavigationBar()
}
private fun setupBottomNavigationBar() {
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)
val navGraphIds = listOf(R.navigation.navigation_home, R.navigation.navigation_add, R.navigation.navigation_card, R.navigation.navigation_pay, R.navigation.navigation_config)
// Setup the bottom navigation view with a list of navigation graphs
val controller = bottomNavigationView.setupWithNavController(
navGraphIds = navGraphIds,
fragmentManager = supportFragmentManager,
containerId = R.id.nav_host_container,
intent = intent
)
// Whenever the selected controller changes, setup the action bar
controller.observe(this, Observer { navController ->
setupActionBarWithNavController(navController)
})
currentNavController = controller
Log.i("controller", "valor es = ${currentNavController!!.value}");
}
override fun onSupportNavigateUp(): Boolean {
Log.i("controller", "support = ${currentNavController?.value?.navigateUp()}");
val navController = findNavController(R.id.nav_host_container)
//return currentNavController?.value?.navigateUp() ?: false
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.nav_camera){
Toast.makeText(this , "Camera Click", Toast.LENGTH_SHORT).show()
//Navigation.findNavController(this, R.id.navigationHome).navigate(R.id.action_navigation_home_to_homeDetalleFragment)
currentNavController?.value?.navigate(R.id.action_navigation_home_to_homeDetalleFragment)
drawerLayout.closeDrawer(Gravity.LEFT)
}
return true;
}
override fun onBackPressed() {
if(drawerLayout.isDrawerOpen(Gravity.LEFT)){
drawerLayout.closeDrawer(Gravity.LEFT)
}else{
super.onBackPressed()
}
}
}
activity_main.xml
<androidx.drawerlayout.widget.DrawerLayout
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"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
android:id="#+id/include_main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/dra_main_content_appbar"/>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/dra_drawer_nav_header"
app:menu="#menu/drawer_navigation" />
</androidx.drawerlayout.widget.DrawerLayout>
dra_main_content_appbar
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".ui.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.Cocktapp.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_activity"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/Theme.Cocktapp.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/dra_content" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
dra_content
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/dra_main_content_appbar">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_container"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
Each element of the BottonNavigationView has a different navigation file: example: navigation_home
<navigation 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:id="#+id/navigationHome"
app:startDestination="#id/navigation_home">
<fragment
android:id="#+id/navigation_home"
android:name="com.cocktapp.cocktapp.ui.home.HomeFragment"
android:label="Home"
tools:layout="#layout/fragment_home" >
<action
android:id="#+id/action_navigation_home_to_homeDetalleFragment"
app:destination="#id/homeDetalleFragment" />
</fragment>
<fragment
android:id="#+id/homeDetalleFragment"
android:name="com.cocktapp.cocktapp.ui.home.HomeDetalleFragment"
android:label="Detalle"
tools:layout="#layout/fragment_home_detalle" />
</navigation>
example: navigation_add
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/navigationAdd"
app:startDestination="#id/navigation_add">
<fragment
android:id="#+id/navigation_add"
android:name="com.cocktapp.cocktapp.ui.add.AddFragment"
android:label="Nuevo"
tools:layout="#layout/fragment_add" >
<action
android:id="#+id/action_navigation_add_to_addDetallekFragment"
app:destination="#id/addDetalleFragment" />
</fragment>
<fragment
android:id="#+id/addDetalleFragment"
android:name="com.cocktapp.cocktapp.ui.add.AddDetalleFragment"
android:label="Detalle"
tools:layout="#layout/fragment_add_detalle" />
</navigation>
All you have to do is:
override fun onNavigationItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.nav_camera){
Toast.makeText(this , "Camera Click", Toast.LENGTH_SHORT).show()
if(currentNavController.currentDestination.id != R.id.homeDetalleFragment){
currentNavController?.value?.navigate(R.id.action_navigation_home_to_homeDetalleFragment)
}
drawerLayout.closeDrawer(Gravity.LEFT)
}
return true;
}
I just want to have my "More" menu point open a BottomSheet:
I'm using the new Android navigation component with a navigation graph, but I can't figure out where I could override the behavior.
My menu.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_home_screen"
android:icon="#drawable/ic_add_white_24dp"
android:title="#string/title_home" />
<item
android:id="#+id/navigation_sas"
android:icon="#drawable/ic_check_white_24dp"
android:title="#string/title_activity_sa" />
<item
android:id="#+id/navigation_profile"
android:icon="#drawable/ic_close_white_24dp"
android:title="#string/title_profile" />
<item
android:id="#+id/navigation_more_menu"
android:icon="#drawable/ic_more_horiz_24"
android:title="#string/title_more_menu" />
</menu>
My nav-graph:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mobile_navigation"
app:startDestination="#id/navigation_home_screen">
<fragment
android:id="#+id/navigation_home_screen"
android:name="com.dev.solidmind.ui.HomeScreenFragment"
android:label="#string/title_home"
tools:layout="#layout/fragment_home_screen" />
<fragment
android:id="#+id/navigation_sas"
android:name="com.dev.solidmind.ui.SA_Fragment"
android:label="#string/title_activity_sa"
tools:layout="#layout/fragment_sa" />
<fragment
android:id="#+id/navigation_profile"
android:name="com.dev.solidmind.ui.ProfileFragment"
android:label="#string/title_profile"
tools:layout="#layout/fragment_profile" />
<dialog
android:id="#+id/navigation_more_menu"
android:label="#string/title_more_menu" />
</navigation>
As you can see I tried adding the more menu BottomSheet as a dialog or some other item, but nothing works.
I added everything in the set-up methods for the navigation component and thought I could override the behavior in the addOnDestinationChangedListener, but it throws an error because it tries to navigate to that menu point:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
BottomNavigationView bottomNavView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home_screen, R.id.navigation_sas, R.id.navigation_profile, R.id.navigation_more_menu)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(bottomNavView, navController);
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
if (destination.getId() == R.id.navigation_home_screen) {
Objects.requireNonNull(getSupportActionBar()).hide();
} else if (destination.getId() == R.id.navigation_more_menu) {
openBottomSheet();
} else {
Objects.requireNonNull(getSupportActionBar()).show();
}
});
}
openBottomSheet method:
public void openBottomSheet() {
View dialogView = getLayoutInflater().inflate(R.layout.main_bottom_sheet_menu, findViewById(R.id.main_root_layout), false);
BottomSheetDialog dialog = new BottomSheetDialog(this);
if (paidContentUnlocked)
adaptBottomSheetToPaidStatus(dialogView);
dialog.setContentView(dialogView);
dialog.show();
}
Can I prevent the navigation and only open my menu instead?
Without having to go back to manually managing Fragments with transactions etc...
I've been able to do by simply surrounding my <fragment> tag with a CoordinatorLayout just like below
activity_main.xml
<LinearLayout
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="vertical">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="#menu/bottom_navigation_menu"
app:labelVisibilityMode="labeled"
/>
</LinearLayout>
MyBottomSheet
class BottomSheetFragment: BottomSheetDialogFragment(), View.OnClickListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = BottomSheetDialog(requireContext(), theme)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_bottom_sheet, container, false)
}
}
OR the Answer of #Naveen Rao
findViewById(R.id.nav_bottom_view).setOnNavigationItemSelectedListener {
// This is to avoid going to startDestination of opening of the BottomSheet
navController.navigate(it.itemId)
true
}
I know this already asked many times, but in my case, I still don't get it.
So I have a navigation drawer that set up in the MainActivity.kt (My app has many fragment that runs on this Activity).
MainActivity.kt
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
lateinit var drawerLayout: DrawerLayout
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
drawerLayout = binding.drawerLayout
//Get navigation controller of this App
val navController = this.findNavController(R.id.myNavHostFragment)
//Lock the Nav drawer
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
NavigationUI.setupWithNavController(binding.navView, navController)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_logout -> {
Toast.makeText(this, "Publication", Toast.LENGTH_SHORT).show()
Log.i("MainActivity", "Sign out clicked!")
}
R.id.nav_messages -> {
Toast.makeText(this, "Publication", Toast.LENGTH_SHORT).show()
}
}
binding.drawerLayout.closeDrawer(GravityCompat.START)
return true
}
// Set up the back button on action bar
override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.myNavHostFragment)
return NavigationUI.navigateUp(navController, drawerLayout)
}
}
This is my Activity_main.xml
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.drawerlayout.widget.DrawerLayout
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/myNavHostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph = "#navigation/navigation"
app:defaultNavHost = "true"
/>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/nav_drawer_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
</layout>
This is the menu layout for the navigation drawer:
nav_drawer_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group>
<item
android:id="#+id/nav_profile"
android:icon="#drawable/ic_person"
android:title="Profile"/>
<item
android:id="#+id/nav_messages"
android:icon="#drawable/ic_people"
android:title="Messages"/>
</group>
<item android:title="Account Settings">
<menu>
<item
android:id="#+id/nav_logout"
android:title="Sign Out"/>
</menu>
</item>
</menu>
This is how the navigation drawer looks like.
Am I missing something ? If there's anything unclear let me know.
You should use setNavigationItemSelectedListener.
Set a listener that will be notified when a menu item is selected.
navigationViewOBJ.setNavigationItemSelectedListener(this)
For DataBinding You should use
binding.navView.setNavigationItemSelectedListener(this)
I was facing the same issue and I changed my code in this manner to get Toast when Menuitems were select.
I removed NavigationView.OnNavigationItemSelectedListener this from
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener
created a variable in MainActivity class in MianActivity.kt
private lateinit var navView : NavigationView
assigned navView variable in override fun onCreate function like this by finding navigation view id like this
navView = findViewById(R.id.nav_menu)
which in your case is in activity_main.xml under this Section
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/nav_drawer_menu"/>
Then I implemented this function for onclick select
navView.setNavigationItemSelectedListener {}
I wrote switch case in this function same as your code and now it is working for me fine.
I am trying to use the Navigation Architecture Component (NavHostFragment) with a Navigation Drawer (widget.NavigationView). I get one of the following two errors.
1) This can happen when selecting an item from the drawer several times:
java.lang.IllegalArgumentException: navigation destination app.myDomain.navdrawertrials:id/action_rootFragment_to_settingsFragment is unknown to this NavController
2) This happens from my real code base that is set up the same way as the simplified sample below AFAICT. Why would a current navigation node not be set?
java.lang.IllegalStateException: no current navigation node
Simplified Code
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
setupToolbar()
setupNavDrawer()
setupNavigation()
}
private fun setupToolbar() {
setSupportActionBar( toolbar )
}
private fun setupNavigation() {
val navController = findNavController( R.id.nav_host_fragment)
setupActionBarWithNavController( navController, main_activity_drawer_layout )
}
private fun setupNavDrawer() {
val toggle = ActionBarDrawerToggle(
this,
main_activity_drawer_layout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
main_activity_drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_drawer.setNavigationItemSelectedListener {
val navController = findNavController( R.id.nav_host_fragment )
when (it.itemId) {
R.id.nav_drawer_root_menu_item -> navController.navigate(R.id.rootFragment)
R.id.nav_drawer_first_menu_item -> navController.navigate(R.id.action_rootFragment_to_firstFragment)
R.id.nav_drawer_settings_menu_item -> navController.navigate(R.id.action_rootFragment_to_settingsFragment)
}
main_activity_drawer_layout.closeDrawer(GravityCompat.START)
true
}
}
override fun onSupportNavigateUp() = findNavController(R.id.nav_host_fragment).navigateUp()
}
main_activity.xml
<android.support.v4.widget.DrawerLayout
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:id="#+id/main_activity_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="#layout/main_activity_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_drawer_header"
app:menu="#menu/nav_drawer_menu" />
</android.support.v4.widget.DrawerLayout>
nav_drawer_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_drawer_root_menu_item"
android:title="To Root" />
<item
android:id="#+id/nav_drawer_first_menu_item"
android:title="To First" />
<item
android:id="#+id/nav_drawer_settings_menu_item"
android:title="To Settings" />
</menu>
main_activity_content.xml
<android.support.design.widget.CoordinatorLayout
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">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
</android.support.design.widget.AppBarLayout>
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:navGraph="#navigation/nav_graph"
app:defaultNavHost="true"
/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
nav_graph.xml
<navigation 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:id="#+id/nav_graph"
app:startDestination="#id/rootFragment">
<fragment
android:id="#+id/rootFragment"
android:name="app.anytune.navdrawertrials.RootFragment"
android:label="root_fragment"
tools:layout="#layout/root_fragment" >
<action
android:id="#+id/action_rootFragment_to_firstFragment"
app:destination="#id/firstFragment" />
<action
android:id="#+id/action_rootFragment_to_settingsFragment"
app:destination="#id/settingsFragment" />
</fragment>
<fragment
android:id="#+id/firstFragment"
android:name="app.anytune.navdrawertrials.FirstFragment"
android:label="first_fragment"
tools:layout="#layout/first_fragment" />
<fragment
android:id="#+id/settingsFragment"
android:name="app.anytune.navdrawertrials.SettingsFragment"
android:label="settings_fragment"
tools:layout="#layout/settings_fragment" />
</navigation>
root_fragment.xml (other nodes are similar empty fragments with just a label)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RootFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Root Fragment" />
</FrameLayout>
Regarding the first error, based on your code, when user select 'first' or 'settings' from drawer he is transferred to 'first' or 'settings' fragment using action_rootFragment_to_firstFragment or action_rootFragment_to_settingsFragment action, but if you try to select again 'first' or 'settings' from drawer there is no action_rootFragment_to_firstFragment or action_rootFragment_to_settingsFragment action inside firstFragment or settingsFragment element inside navigation graph.
The solution is to change:
when (it.itemId) {
R.id.nav_drawer_root_menu_item -> navController.navigate(R.id.rootFragment)
R.id.nav_drawer_first_menu_item -> navController.navigate(R.id.action_rootFragment_to_firstFragment)
R.id.nav_drawer_settings_menu_item -> navController.navigate(R.id.action_rootFragment_to_settingsFragment)
}
to:
when (it.itemId) {
R.id.nav_drawer_root_menu_item -> navController.navigate(R.id.rootFragment)
R.id.nav_drawer_first_menu_item -> navController.navigate(R.id.firstFragment)
R.id.nav_drawer_settings_menu_item -> navController.navigate(R.id.settingsFragment)
}
The better solution is to tie destinations to menu-driven UI components(in your case drawer), change your menu items id to same as destinations id's, like this:
<item
android:id="#+id/rootFragment"
android:title="To Root" />
<item
android:id="#+id/firstFragment"
android:title="To First" />
<item
android:id="#+id/settingsFragment"
android:title="To Settings" />
and add
setupWithNavController(nav_view, navController )
inside your main activity, instead of
nav_drawer.setNavigationItemSelectedListener {
val navController = findNavController( R.id.nav_host_fragment )
when (it.itemId) {
R.id.nav_drawer_root_menu_item -> navController.navigate(R.id.rootFragment)
R.id.nav_drawer_first_menu_item -> navController.navigate(R.id.action_rootFragment_to_firstFragment)
R.id.nav_drawer_settings_menu_item -> navController.navigate(R.id.action_rootFragment_to_settingsFragment)
}
main_activity_drawer_layout.closeDrawer(GravityCompat.START)
true
}
2) If the crash occurs on orientation change. Use the below on the activity
upgrade navigation version module to 2.2.0 or above
implementation "androidx.navigation:navigation-fragment-ktx:2.2.0"
implementation "androidx.navigation:navigation-ui-ktx:2.2.0"