-1

I have multiple text lines in single textView. It is like this:

Hello\n www.google.com\n

Since I have set android:autoLink="web" thus www.google.com opens in the browser of my mobile. However, I want to know when this text is pressed so that I can use the value and open the link since I want to parse the output of this link in another activity. But I am not able to call a custom method based on the click of this URL, it only opens the browser by default.

Alternatively, if I could get what text is clicked it would be great. Since every text line ends with "\n" I want to get that line. Let's say in above example I click H, I want to get Hello so that I can use it for other purposes. Any way to do this?

Thanks.

1 Answers1

0

android:autoLink="web" is an abstraction which handles the onClicks on your behalf. If you intent to handle the clicks by yourself, then you have to do the custom implementation for it.

You can follow this SO which describes this approach as follows:

protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span)
{
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            // Do something with span.getURL() to handle the link click...
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}

protected void setTextViewHTML(TextView text, String html)
{
    CharSequence sequence = Html.fromHtml(html);
    SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
    URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);   
    for(URLSpan span : urls) {
        makeLinkClickable(strBuilder, span);
    }
    text.setText(strBuilder);
    text.setMovementMethod(LinkMovementMethod.getInstance());       
}
Sagar
  • 23,903
  • 4
  • 62
  • 62