Skip to content
Advertisement

Make HTML anchor links start a new activity in Android Java

I have a String that contains HTML tags which I display in a TextView

Spanned text;
String htmlText = "<p dir="ltr">It was a great day with <a href="52">Julius</a> and <a href="18">Stanley</a></p>";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
    text = Html.fromHtml(htmlText, Html.FROM_HTML_MODE_COMPACT);
else
    text = Html.fromHtml(htmlText);

textView.setText(text);

Now I want those links to be clickable, and not just clickable, but to startup an Activity when clicked. The href attributes have numbers which I want to pass as a parameter to my Intent to start my Activity.

I use JSoup to extract the values of the href like this:

Document doc = Jsoup.parse(htmlText, "UTF-8");
Elements elements = doc.getElementsByTag("a");
for(int e = 0; e < elements.size(); e++){
    Element element = elements.get(e);
    String href = element.attr("href");
}

So I was hoping I can get a ClickEventListener on the links and start the activity like this:

element.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(context, NewActivity.class);
        Bundle userParams = new Bundle();
        userParams.putString("userId", href);
        intent.putExtras(userParams);
        startActivity(intent);
    }
});

I know element is not a ViewGroup so it can’t be done like my code shows, but is there any possible way of achieving this?

Advertisement

Answer

Search and I got an answer from here

String htmlText = "<p dir="ltr">It was a great day with <a href="52">Julius</a> and <a href="18">Stanley</a></p>";
CharSequence sequence = Html.fromHtml(htmlText);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);   
for(URLSpan span : urls) {
    makeLinkClickable(strBuilder, span);
}
textView.setText(strBuilder);
textView.setMovementMethod(LinkMovementMethod.getInstance());

And then the makeLinkClickable method to handle the links

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) {
            String href span.getURL();
            Intent intent = new Intent(context, NewActivity.class);
            Bundle userParams = new Bundle();
            userParams.putString("userId", href);
            intent.putExtras(userParams);
            startActivity(intent);
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement