Search code examples
androidwebviewautolink

Multiple URLs in TextView


In my app I have one textview that contains multiple URLs. I have to open that in my app only if I used

android:autoLink="web"
android:clickable="true"

Here it opens in browser but I have to open in my Webview.


Solution

  • Please check the below code.

    I had tried using below code.

    TextView tv = ....
    tv.setMovementMethod(LinkMovementMethod.getInstance());
    
        String content = tv.getText().toString();
        List<String> links = new ArrayList<String>();
    
        Pattern p = Patterns.WEB_URL;
        Matcher m = p.matcher(content);
        while (m.find()) {
            String urlStr = m.group();
            links.add(urlStr);
        }
    
        SpannableString f = new SpannableString(content);
    
        for (int i = 0; i < links.size(); i++) {
            final String url = links.get(i);
    
            f.setSpan(new InternalURLSpan(new OnClickListener() {
                public void onClick(View v) {
                    Context ctx = v.getContext();
                    String urlToOpen = url;
                    if (!urlToOpen.startsWith("http://") || !urlToOpen.startsWith("https://"))
                        urlToOpen = "http://" + urlToOpen;
                    openURLInBrowser(urlToOpen, ctx);
                }
            }), content.indexOf(url), content.indexOf(url) + url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    
        tv.setText(f);
    

    Hope It will help you.

    InternalURLSpan class

    public class InternalURLSpan extends ClickableSpan {
        OnClickListener mListener;
    
        public InternalURLSpan(OnClickListener listener) {
            mListener = listener;
        }
    
        @Override
        public void onClick(View widget) {
            mListener.onClick(widget);
        }
    }