0

I have a TextView that applied Linkify to that to create my links.

Linkify.addLinks(mTextView, Linkify.ALL);

Now when users click on links, apps open links in native browser. But i want to users have this option to select their favorite browser by showing "Complete action using" dialog.

How can add this feature to linkified links?

MAY3AM
  • 1,182
  • 3
  • 17
  • 42

1 Answers1

1

You can use the ClickableSpan, and set the textview with it

public class LinkSpan extends ClickableSpan {

  private OnClickListener listener;

  public LinkSpan(OnClickListener listener){
    this.listener = listener;
  }

  @Override
  public void onClick(View widget) {
    listener.onClick(widget);
  }
}

public class LinkifyUtil {

  private Activity activity;

  public LinkifyUtil(Activity activity){
    this.activity = activity; 
  }

  public void addAutoChooserLink(final Intent intent,TextView text){
    String source = text.getText().toString();
    String pattern = "Android";
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(source);
    SpannableString s = new SpannableString(source);
    while(m.find()){
      s.setSpan(new LinkSpan(new OnClickListener(){

        @Override
        public void onClick(View v) {
          //you can define the intent
          intent.setAction(Intent.ACTION_VIEW);
          intent.setData(Uri.parse("http://developer.android.com"));
          Intent.createChooser(intent, "Choose App");
          activity.startActivity(intent);
        }
      }), m.start(), m.start()+pattern.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    text.setText(s);
    text.setMovementMethod(LinkMovementMethod.getInstance());
  }  
}

You can use the LinkifyUtil like this:

Intent intent = new Intent();       
LinkifyUtil linkify = new LinkifyUtil(this);
linkify.addAutoChooserLink(intent, text);
ivan.sim
  • 8,972
  • 8
  • 47
  • 63
wqycsu
  • 290
  • 2
  • 16