Search code examples
javaandroidkotlinandroid-architecture-navigation

Android: Linking to URL in Navigation Drawer


I am using the Navigation Components library for my Navigation Drawer. I want one item in said drawer to link to an external Website. The offical documentation doesn't say anything about external links. How do I implement that?

I could create a temporary fragment and navigate to that first but this solution is not very elegant in my opinion.


Solution

  • The line

    NavigationUI.setupWithNavController(navigationView, navController);
    

    Calls setNavigationItemSelectedListener internally to connect destinations to menu items - this is how a new destination is launched when you click a menu item. Navigation supports <activity> destinations, allowing you to start an activity when clicking on a menu item. You'd add an activity destination to your graph that uses the same id as your menu item:

    <activity
      android:id="@+id/nav_login_activity"
      app:action="android.intent.action.VIEW"
      app:data="https://www.your_url_here.com"/>
    

    Then the default setupWithNavController will call startActivity for you.