Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

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

I have a textView and text like

"This is the Simple Text with KeyWord and the Link to browse"

in the above text i want to make..

clicking on the Link goes to open that URL AND clicking on that KeyWord open a new Activity in my application

also, There is an click event for the Whole TextView even.

Please help me finding a solution. Thank You, MKJParekh

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...