I know that if you put a link in a textview it will work but if I want to display for example:
google stackoverflow
and not the whole link(just the tag) How do i make those links clickable?
Just like Buttons and ImageViews we can add onClickListeners to TextViews by simply adding the attribute android:onClick="myMethod" to your TextView XML tag. The other way, TextView tv = (TextView) this.
Create a hyperlink to a location on the webSelect the text or picture that you want to display as a hyperlink. Press Ctrl+K. You can also right-click the text or picture and click Link on the shortcut menu. In the Insert Hyperlink box, type or paste your link in the Address box.
You could have two separate TextViews and you could align them accordingly in your layout if needed:
Text1.setText( Html.fromHtml( "<a href=\"http://www.google.com\">google</a> ")); Text1.setMovementMethod(LinkMovementMethod.getInstance()); Text2.setText( Html.fromHtml( "<a href=\"http://www.stackoverflow.com\">stackoverflow</a> ")); Text2.setMovementMethod(LinkMovementMethod.getInstance());
Then if you want to strip the "link underline". Create a class:
public class URLSpanNoUnderline extends URLSpan { public URLSpanNoUnderline(String url) { super(url); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }
Then add this method in your main Activity class where you have the TextViews
private void stripUnderlines(TextView textView) { Spannable s = new SpannableString(textView.getText()); URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); for (URLSpan span: spans) { int start = s.getSpanStart(span); int end = s.getSpanEnd(span); s.removeSpan(span); span = new URLSpanNoUnderline(span.getURL()); s.setSpan(span, start, end, 0); } textView.setText(s); }
And then just call this after you initialised the TextViews (in your onCreate):
stripUnderlines(Text1); stripUnderlines(Text2);
TextView t2 = (TextView) findViewById(R.id.textviewidname); t2.setMovementMethod(LinkMovementMethod.getInstance());
and
<string name="google_stackoverflow"><a href="https://stackoverflow.com/questions/9852184/android-textview-hyperlink?rq=1">google stack overflow</a></string>
The link is, "Android: textview hyperlink"
and the tag is, "google stack overflow"
Define the first code block in your java and the second code block in your strings.xml file. Also, be sure to reference the id of the textView from your page layout in your java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With