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?
2
Answers
simply use the listener of the drawer and on the required item use
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 usenew Intent
let me know if you need have in converting this to javaThis line
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:Then the default
setupWithNavController
will callstartActivity
for you.