Android Linkify text – Spannable Text in Single Text View – As like Twitter tweet

What you can do is create a Custom ClickableSpan as below,

class MyCustomSpannable extends ClickableSpan
{
    String Url;
    public MyCustomSpannable(String Url) {
        this.Url = Url;
    }
    @Override
    public void updateDrawState(TextPaint ds) {
            // Customize your Text Look if required
        ds.setColor(Color.YELLOW);
        ds.setFakeBoldText(true);
        ds.setStrikeThruText(true);
        ds.setTypeface(Typeface.SERIF);
        ds.setUnderlineText(true);
        ds.setShadowLayer(10, 1, 1, Color.WHITE);
        ds.setTextSize(15);
    }
    @Override
    public void onClick(View widget) {
    }
    public String getUrl() {
        return Url;
    }
}

And the use its onClick() for opening an Activity or URL. I am adding a demo for loading a URL in WebView.

String text = "http://www.google.co.in/";
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(text);
MyCustomSpannable customSpannable = new MyCustomSpannable(
                                               "http://www.google.co.in/"){

            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(customSpannable.getUrl()));
                startActivity(intent);
            }
        };
        stringBuilder.setSpan(customSpannable, 0, text.length(),
                                         Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        textView.setText( stringBuilder, BufferType.SPANNABLE );
        textView.setMovementMethod(LinkMovementMethod.getInstance());

Leave a Comment