6

I have simple code that opens URL in a browser:

startActivity(Intent(
    Intent.ACTION_VIEW, Uri.parse(resources.getString(R.string.application_url))
))

How can I convert this to the navigation component item?

Do I need to build custom navigator for this, or navigation component has something built in for such case?

RKRK
  • 1,284
  • 5
  • 14
  • 18
antanas_sepikas
  • 5,644
  • 4
  • 36
  • 67

3 Answers3

8

I figured it out, for this simple case custom navigator is not needed all you need is to create navigation endpoint:

<activity
    android:id="@+id/navigation_endpoint_id"
    app:action="android.intent.action.VIEW"
    app:data="@string/application_url"/>
antanas_sepikas
  • 5,644
  • 4
  • 36
  • 67
  • How can you navigate with dynamic web urls; I mean with the url user provide in the app during run-time? – Mustaqode Nov 19 '20 at 06:26
  • 3
    I don't think that's possible using the navigation component or at least within the navigation graph scope. Of course, you could dynamically create a navigation graph, but then you would need to recreate your activity which isn't the most convenient option. The general rule I've figured out using navigation component for some time now, that for activities it's better just to use old school intents. – antanas_sepikas Nov 19 '20 at 06:35
2

For Dynamic Uri, we can pass the data like this:

<activity
    android:id="@+id/whatsappRedirectionActivity"
    app:action="android.intent.action.VIEW"
    app:dataPattern="https://wa.me/{number}">
    <argument
         android:name="number"
         app:argType="string" />
</activity>

This needs to include to navigation graph where you want to redirection. Using this we can use safeargs actions as well.

Rahul Mishra
  • 583
  • 7
  • 17
0

If you are using Navigation drawer, you can set this programmatically like this. This way you can set custom function for a particular navigation item without losing navigation graph advantages

navigationView.setNavigationItemSelectedListener {item->
                drawerLayout.closeDrawer(GravityCompat.START)
                when(item.itemId){
                    R.id.navigation_rate -> {
                        startActivity(Intent(
                                Intent.ACTION_VIEW, Uri.parse(resources.getString(R.string.app_playstore_url))
                        ))
                        return@setNavigationItemSelectedListener true
                    }
                    else  -> NavigationUI.onNavDestinationSelected(item, navController)
                }
            }