Home > Net >  How do I add a link to items in menu for navigation drawer in android studio?
How do I add a link to items in menu for navigation drawer in android studio?

Time:10-24

I am trying to add a link to my text so that when the user clicks the text it redirects him to a website, the text is under an item tag which is under a menu tag in my xml file, but I don't know how to make this work. This is what I added so far. This is the xml file for the content of my navigation drawer, the navigation drawer code is in my activty_main.xml which is already functioning.

 <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="HardcodedText">

    <item
        android:id="@ id/nav_one"
        android:title="link3"
        android:text="@string/hyperlink"/>

    <item
        android:id="@ id/nav_two"
        android:title="Settings" />

    <item
        android:id="@ id/nav_three"
        android:title="link1" />

</menu>

and this is what I added in my string.xml file

<string name="hyperlink"><a href="https://www.youtube.com/">start</a></string>

however the problem is that I don't know how to make it work. I don't know what to add to my mainactivity to make this work. This is what I added to my main activity but it obviously doesn't work.

MenuItem menuItem = findViewById(R.id.nav_one);
    menuItem.setMovementMethod(LinkMovementMethod.getInstance());

What do I have to change and add to make this work?

CodePudding user response:

simply use the listener of the drawer and on the required item use

startActivity(Intent(Intent.ACTION_VIEW,Uri.parse(your link here in string format)))

it will open the link in the default browser of the device , this code is kotlin by the way. but java is same also just have to use the java syntax like instead of simple Intent you have to use new Intent let me know if you need have in converting this to java

CodePudding user response:

This 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.

  • Related