简体   繁体   中英

How to use autoLink in textView and custom URLSpan both together?

I have a textView like this:

<TextView
  android:id="@+id/note_viewer"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:autoLink="email|web|phone"
  android:textSize="15sp" />

And a Spannable string like this:

String input = note.getText();
SpannableStringBuilder builder = new SpannableStringBuilder(input);
Pattern pattern = Pattern.compile(XTAG_PATTERN);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
  int start = matcher.start();
  int end = matcher.end();
  String text = input.subSequence(start, end).toString();
  ClickableURLSpan url = new ClickableURLSpan(text, getActivity()
    .getApplicationContext(), this);
  builder.setSpan(url, start, end, 0);
}
noteView.setText(builder);
noteView.setMovementMethod(LinkMovementMethod.getInstance());

And a custom `URLSpan class like this:

public class ClickableURLSpan extends URLSpan {
  Context context;
  NoteViewFragment noteViewFragment;
  public ClickableURLSpan(String url,Context c, NoteViewFragment noteViewFragment) {
    super(url);
    context=c;
    this.noteViewFragment=noteViewFragment;
}
@Override
public void onClick(View widget) {
  String clickedText = getURL();
  Intent i=new Intent(context,SearchActivity.class);
  i.putExtra("tag", clickedText);
  noteViewFragment.startActivity(i);
}}

But when I'm using autolink my custom clickable span doesn't work. How do I use both autolink and my own clickable span together?

Change spanable string as:

            String input = note.getText();
            Spannable spannable = new SpannableString(Html.fromHtml(input));
            Pattern pattern = Pattern.compile(XTAG_PATTERN);

            Linkify.addLinks(spannable, pattern, "");
            URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
            for (URLSpan urlSpan : spans) {
                ClickableURLSpan linkSpan = new ClickableURLSpan(text, getActivity().getApplicationContext(), this);
                int spanStart = spannable.getSpanStart(urlSpan);
                int spanEnd = spannable.getSpanEnd(urlSpan);
                spannable.setSpan(linkSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannable.removeSpan(urlSpan);
            }
            textview.setMovementMethod(EnhancedLinkMovementMethod.getInstance());
            noteView.setText(spannable, TextView.BufferType.SPANNABLE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM