wrap URL in a clickable SpannableString - Android android.text

Android examples for android.text:SpannableString

Description

wrap URL in a clickable SpannableString

Demo Code

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.view.View;

public class Main{

    public static SpannableString wrapText(final Context context,
            final String text) {
        final int index = text.indexOf("http");
        if (index == -1) {
            return new SpannableString(text);
        }/*from   w w w  .j a  va  2  s.c  o  m*/
        final SpannableString ss = new SpannableString(text);
        ss.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Uri uri = Uri.parse(text.substring(index, text.length()));
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
            }
        }, index, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }

}

Related Tutorials