Home » Android » android – TextView Hyperlink is not working?

android – TextView Hyperlink is not working?

Posted by: admin June 15, 2020 Leave a comment

Questions:

Why TextView Hyperlink is not working.

Using hyperlink as inside the custom dialog box.

The hyperlink is not appear.

Where i am mistaken. How do solve it. Give me guidance.

XML code is

<TextView
android:id="@+id/google_Link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:padding="10dip"
android:textSize="20dip"
android:linksClickable="true"  
android:autoLink="all"
android:textColorLink="#306EFF"
android:text="" />

Android Code is

TextView googleLink = ( TextView ) layout.findViewById( R.id.google_Link );
googleLink.setClickable(true);
googleLink.setMovementMethod(LinkMovementMethod.getInstance());
googleLink.setText( Html.fromHtml( "<a href=`http://www.google.co.in`>Google</a>" ) );

Android Manifest Code is

<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

Thank in advance.

How to&Answers:

Replace only this link,it will work:

TextView textView=(TextView) findViewById(R.id.link);
textView.setClickable(true);
String linkTxt=getResources().getString(R.string.link);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(Html.fromHtml( linkTxt));

Add this in strings.xml:

<string name="link">&lt;a href=http://www.google.co.in&gt;Google&lt;/a&gt;</string>

Answer:

The Best solution to this issue is:
First, create a Textview.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/link"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="@string/developed_by_bracecodes"/>

Then add text to your Textview from strings.xml like below:

<string name="developed_by_bracecodes"><a href="http://www.bracecodes.com">Developed by Bracecodes</a>  </string>

N.B: don’t forget to add http:// before your link

Then add these lines in your java code:

TextView link = findViewById(R.id.link);
link.setMovementMethod(LinkMovementMethod.getInstance());

Happy Coding!
Thanks!

Answer:

It is not working because you can’t set a href to a TextView.

You’ll need to set an OnClickListener which has this in it’s onClick method:

String url = "http://www.google.co.in";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

After that you can set the listener to your TextView like this: googleLink.setOnClickListener(myListener);

Then run the app again and the click should be handled correctly.