android.text.style.URLSpan Java Examples

The following examples show how to use android.text.style.URLSpan. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: mollyim-android   Author: mollyim   File: ConversationItem.java    License: GNU General Public License v3.0 6 votes vote down vote up
private SpannableString linkifyMessageBody(SpannableString messageBody, boolean shouldLinkifyAllLinks) {
  int     linkPattern = Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS;
  boolean hasLinks    = Linkify.addLinks(messageBody, shouldLinkifyAllLinks ? linkPattern : 0);

  if (hasLinks) {
    Stream.of(messageBody.getSpans(0, messageBody.length(), URLSpan.class))
          .filterNot(url -> LinkPreviewUtil.isLegalUrl(url.getURL()))
          .forEach(messageBody::removeSpan);

    URLSpan[] urlSpans = messageBody.getSpans(0, messageBody.length(), URLSpan.class);

    for (URLSpan urlSpan : urlSpans) {
      int start = messageBody.getSpanStart(urlSpan);
      int end = messageBody.getSpanEnd(urlSpan);
      messageBody.setSpan(new LongClickCopySpan(urlSpan.getURL()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
  }
  return messageBody;
}
 
Example #2
Source Project: MHViewer   Author: axlecho   File: GalleryCommentsScene.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
    Activity activity = getActivity2();
    if (null == activity) {
        return false;
    }

    RecyclerView.ViewHolder holder = parent.getChildViewHolder(view);
    if (holder instanceof CommentHolder) {
        CommentHolder commentHolder = (CommentHolder) holder;
        ClickableSpan span = commentHolder.comment.getCurrentSpan();
        commentHolder.comment.clearCurrentSpan();

        if (span instanceof URLSpan) {
            UrlOpener.openUrl(activity, ((URLSpan) span).getURL(), true);
            return true;
        }
    }

    showCommentDialog(position);

    return true;
}
 
Example #3
Source Project: indigenous-android   Author: swentel   File: TimelineDetailActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Link clickable.
 *
 * @param strBuilder
 *   A string builder.
 * @param span
 *   The span with url.
 */
private void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span) {
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(@NonNull View view) {
            try {
                CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
                intentBuilder.setToolbarColor(ContextCompat.getColor(TimelineDetailActivity.this, R.color.colorPrimary));
                intentBuilder.setSecondaryToolbarColor(ContextCompat.getColor(TimelineDetailActivity.this, R.color.colorPrimaryDark));
                CustomTabsIntent customTabsIntent = intentBuilder.build();
                customTabsIntent.intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                customTabsIntent.launchUrl(TimelineDetailActivity.this, Uri.parse(span.getURL()));
            }
            catch (Exception ignored) { }
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}
 
Example #4
Source Project: indigenous-android   Author: swentel   File: TimelineListAdapter.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Link clickable.
 *
 * @param strBuilder
 *   A string builder.
 * @param span
 *   The span with url.
 */
private void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span) {
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            try {
                CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
                intentBuilder.setToolbarColor(ContextCompat.getColor(context, R.color.colorPrimary));
                intentBuilder.setSecondaryToolbarColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                CustomTabsIntent customTabsIntent = intentBuilder.build();
                customTabsIntent.intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                customTabsIntent.launchUrl(context, Uri.parse(span.getURL()));
            }
            catch (Exception ignored) { }
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}
 
Example #5
Source Project: imsdk-android   Author: qunarcorp   File: IMChatBaseView.java    License: MIT License 6 votes vote down vote up
private void handleUrlSpan() {
    mTimeTextView.setMovementMethod(LinkMovementMethod.getInstance());
    CharSequence text = mTimeTextView.getText();
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
    if (text instanceof Spannable) {
        int end = text.length();
        Spannable spannable = (Spannable) mTimeTextView.getText();
        URLSpan[] urlSpans = spannable.getSpans(0, end, URLSpan.class);
        if (urlSpans.length == 0) {
            return;
        }
        // 循环遍历并拦截
        for (URLSpan uri : urlSpans) {
            String url = uri.getURL();
            if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
                CustomUrlSpan customUrlSpan = new CustomUrlSpan(context, url);
                spannableStringBuilder.setSpan(customUrlSpan, spannable.getSpanStart(uri),
                        spannable.getSpanEnd(uri), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            }
            spannableStringBuilder.removeSpan(uri);
        }
        mTimeTextView.setText(spannableStringBuilder);
    }
}
 
Example #6
Source Project: Hews   Author: leavjenn   File: CommentAdapter.java    License: MIT License 6 votes vote down vote up
private void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span) {
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            Uri uri = Uri.parse(span.getURL());
            CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
            Utils.setupIntentBuilder(intentBuilder, mContext,
                ((CommentsActivity) mContext).getSharedPreferences());
            ChromeCustomTabsHelper.openCustomTab((Activity) mContext, intentBuilder.build(),
                uri, null);
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}
 
Example #7
Source Project: edx-app-android   Author: edx   File: DiscussionTextUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Renders various HTML elements and plain hyperlinks in the given HTML to clickable items
 * while applying it on the given {@link TextView}.
 *
 * @param textView The {@link TextView} which will render the given HTML.
 * @param html     The HTML to render.
 */
public static void renderHtml(@NonNull TextView textView, @NonNull String html) {
    Spanned spannedHtml = DiscussionTextUtils.parseHtml(html);
    URLSpan[] urlSpans = spannedHtml.getSpans(0, spannedHtml.length(), URLSpan.class);
    textView.setAutoLinkMask(Linkify.ALL);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(spannedHtml);

    SpannableString viewText = (SpannableString) textView.getText();
    for (final URLSpan spanObj : urlSpans) {
        final int start = spannedHtml.getSpanStart(spanObj);
        final int end = spannedHtml.getSpanEnd(spanObj);
        final int flags = spannedHtml.getSpanFlags(spanObj);
        viewText.setSpan(spanObj, start, end, flags);
    }
}
 
Example #8
Source Project: Knife   Author: mthli   File: KnifeText.java    License: Apache License 2.0 6 votes vote down vote up
protected boolean containLink(int start, int end) {
    if (start > end) {
        return false;
    }

    if (start == end) {
        if (start - 1 < 0 || start + 1 > getEditableText().length()) {
            return false;
        } else {
            URLSpan[] before = getEditableText().getSpans(start - 1, start, URLSpan.class);
            URLSpan[] after = getEditableText().getSpans(start, start + 1, URLSpan.class);
            return before.length > 0 && after.length > 0;
        }
    } else {
        StringBuilder builder = new StringBuilder();

        for (int i = start; i < end; i++) {
            if (getEditableText().getSpans(i, i + 1, URLSpan.class).length > 0) {
                builder.append(getEditableText().subSequence(i, i + 1).toString());
            }
        }

        return getEditableText().subSequence(start, end).toString().equals(builder.toString());
    }
}
 
Example #9
Source Project: EhViewer   Author: seven332   File: Html.java    License: Apache License 2.0 6 votes vote down vote up
private static void endA(SpannableStringBuilder text) {
    int len = text.length();
    Object obj = getLast(text, Href.class);
    int where = text.getSpanStart(obj);

    text.removeSpan(obj);

    if (where != len) {
        Href h = (Href) obj;

        if (h.mHref != null) {
            text.setSpan(new URLSpan(h.mHref), where, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}
 
Example #10
Source Project: talk-android   Author: jianliaoim   File: MessageFormatter.java    License: MIT License 6 votes vote down vote up
public static Spannable formatURLSpan(Spannable s) {
    Linkify.addLinks(s, Linkify.WEB_URLS);
    URLSpan[] urlSpans = s.getSpans(0, s.length(), URLSpan.class);
    for (URLSpan urlSpan : urlSpans) {
        final String url = urlSpan.getURL();
        final Matcher m = chinesePattern.matcher(url);
        if (m.find()) {
            s.removeSpan(urlSpan);
            continue;
        }
        int start = s.getSpanStart(urlSpan);
        int end = s.getSpanEnd(urlSpan);
        s.removeSpan(urlSpan);
        s.setSpan(new TalkURLSpan(urlSpan.getURL(), ThemeUtil.getThemeColor(MainApp.CONTEXT.
                        getResources(), BizLogic.getTeamColor())), start, end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return s;
}
 
Example #11
Source Project: ResearchStack   Author: ResearchStack   File: TextViewLinkHandler.java    License: Apache License 2.0 6 votes vote down vote up
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
    if (event.getAction() != MotionEvent.ACTION_UP) {
        return super.onTouchEvent(widget, buffer, event);
    }

    int x = (int) event.getX();
    int y = (int) event.getY();

    x -= widget.getTotalPaddingLeft();
    y -= widget.getTotalPaddingTop();

    x += widget.getScrollX();
    y += widget.getScrollY();

    Layout layout = widget.getLayout();
    int line = layout.getLineForVertical(y);
    int off = layout.getOffsetForHorizontal(line, x);

    URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
    if (link.length != 0) {
        onLinkClick(link[0].getURL());
    }
    return true;
}
 
Example #12
Source Project: memoir   Author: ronak-manglani   File: ConverterSpannedToHtml.java    License: Apache License 2.0 6 votes vote down vote up
private void handleEndTag(CharacterStyle style) {
    if (style instanceof URLSpan) {
        mOut.append("</a>");
    } else if (style instanceof TypefaceSpan) {
        mOut.append("</font>");
    } else if (style instanceof ForegroundColorSpan) {
        mOut.append("</font>");
    } else if (style instanceof BackgroundColorSpan) {
        mOut.append("</font>");
    } else if (style instanceof AbsoluteSizeSpan) {
        mOut.append("</font>");
    } else if (style instanceof StrikethroughSpan) {
        mOut.append("</strike>");
    } else if (style instanceof SubscriptSpan) {
        mOut.append("</sub>");
    } else if (style instanceof SuperscriptSpan) {
        mOut.append("</sup>");
    } else if (style instanceof UnderlineSpan) {
        mOut.append("</u>");
    } else if (style instanceof BoldSpan) {
        mOut.append("</b>");
    } else if (style instanceof ItalicSpan) {
        mOut.append("</i>");
    }
}
 
Example #13
Source Project: memoir   Author: ronak-manglani   File: ConverterSpannedToHtml.java    License: Apache License 2.0 6 votes vote down vote up
private void handleEndTag(CharacterStyle style) {
    if (style instanceof URLSpan) {
        mOut.append("</a>");
    } else if (style instanceof TypefaceSpan) {
        mOut.append("</font>");
    } else if (style instanceof ForegroundColorSpan) {
        mOut.append("</font>");
    } else if (style instanceof BackgroundColorSpan) {
        mOut.append("</font>");
    } else if (style instanceof AbsoluteSizeSpan) {
        mOut.append("</font>");
    } else if (style instanceof StrikethroughSpan) {
        mOut.append("</strike>");
    } else if (style instanceof SubscriptSpan) {
        mOut.append("</sub>");
    } else if (style instanceof SuperscriptSpan) {
        mOut.append("</sup>");
    } else if (style instanceof UnderlineSpan) {
        mOut.append("</u>");
    } else if (style instanceof BoldSpan) {
        mOut.append("</b>");
    } else if (style instanceof ItalicSpan) {
        mOut.append("</i>");
    }
}
 
Example #14
Source Project: materialup   Author: goodev   File: HtmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse the given input using {@link TouchableUrlSpan}s
 * rather than vanilla {@link URLSpan}s so that they respond to touch.
 *
 * @param input
 * @param linkTextColor
 * @param linkHighlightColor
 * @return
 */
public static Spanned parseHtml(String input,
                                ColorStateList linkTextColor,
                                @ColorInt int linkHighlightColor) {
    SpannableStringBuilder spanned = (SpannableStringBuilder) Html.fromHtml(input);

    // strip any trailing newlines
    while (spanned.charAt(spanned.length() - 1) == '\n') {
        spanned = spanned.delete(spanned.length() - 1, spanned.length());
    }

    URLSpan[] urlSpans = spanned.getSpans(0, spanned.length(), URLSpan.class);
    for (URLSpan urlSpan : urlSpans) {
        int start = spanned.getSpanStart(urlSpan);
        int end = spanned.getSpanEnd(urlSpan);
        spanned.removeSpan(urlSpan);
        // spanned.subSequence(start, start + 1) == "@" TODO send to our own user activity...
        // when i've written it
        spanned.setSpan(new TouchableUrlSpan(urlSpan.getURL(), linkTextColor,
                linkHighlightColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return spanned;
}
 
Example #15
Source Project: Tehreer-Android   Author: Tehreer   File: LinkableLabel.java    License: Apache License 2.0 6 votes vote down vote up
private URLSpan urlSpanAtIndex(int charIndex) {
    Spanned spanned = getSpanned();
    ComposedFrame composedFrame = getComposedFrame();

    if (spanned == null || composedFrame == null) {
        return null;
    }
    if (charIndex < composedFrame.getCharStart() || charIndex >= composedFrame.getCharEnd()) {
        return null;
    }

    URLSpan[] spans = spanned.getSpans(charIndex, charIndex, URLSpan.class);
    if (spans != null && spans.length > 0) {
        return spans[0];
    }

    return null;
}
 
Example #16
Source Project: BigApp_Discuz_Android   Author: BigAppOS   File: AdapterActManage.java    License: Apache License 2.0 6 votes vote down vote up
private void setLinkClickable(final SpannableStringBuilder clickableHtmlBuilder,
                              final URLSpan urlSpan) {
    int start = clickableHtmlBuilder.getSpanStart(urlSpan);
    int end = clickableHtmlBuilder.getSpanEnd(urlSpan);
    int flags = clickableHtmlBuilder.getSpanFlags(urlSpan);
    clickableHtmlBuilder.setSpan(new ClickableSpan() {
        public void onClick(View view) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(urlSpan.getURL()));
                context.startActivity(intent);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }, start, end, flags);
}
 
Example #17
Source Project: tindroid   Author: tinode   File: SpanFormatter.java    License: Apache License 2.0 6 votes vote down vote up
private TreeNode handleButton(final Map<String,Object> data, final Object content) {
    // This is needed for button shadows.
    mContainer.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

    DisplayMetrics metrics = mContainer.getContext().getResources().getDisplayMetrics();
    // Size of a DIP pixel.
    float dipSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1.0f, metrics);

    // Create BorderSpan.
    final TreeNode span = new TreeNode(
            (CharacterStyle) new BorderedSpan(mContainer.getContext(), mFontSize, dipSize),
            (CharSequence) null);

    // Wrap URLSpan into BorderSpan.
    span.addNode(new URLSpan("") {
        @Override
        public void onClick(View widget) {
            if (mClicker != null) {
                mClicker.onClick("BN", data);
            }
        }
    }, content);

    return span;
}
 
Example #18
Source Project: android-proguards   Author: yongjhih   File: HtmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static SpannableStringBuilder linkifyPlainLinks(
        CharSequence input,
        ColorStateList linkTextColor,
        @ColorInt int linkHighlightColor) {
    final SpannableString plainLinks = new SpannableString(input); // copy of input

    // Linkify doesn't seem to work as expected on M+
    // TODO: figure out why
    //Linkify.addLinks(plainLinks, Linkify.WEB_URLS);

    final URLSpan[] urlSpans = plainLinks.getSpans(0, plainLinks.length(), URLSpan.class);

    // add any plain links to the output
    final SpannableStringBuilder ssb = new SpannableStringBuilder(input);
    for (URLSpan urlSpan : urlSpans) {
        ssb.removeSpan(urlSpan);
        ssb.setSpan(new TouchableUrlSpan(urlSpan.getURL(), linkTextColor, linkHighlightColor),
                plainLinks.getSpanStart(urlSpan),
                plainLinks.getSpanEnd(urlSpan),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return ssb;
}
 
Example #19
Source Project: Tok-Android   Author: InsightIM   File: MsgTextView.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void replaceAutoLinkSpan() {
    Spannable spannable = (Spannable) this.getText();
    URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);

    for (URLSpan span : spans) {
        int linkType = -1;
        String url = span.getURL();
        int index = spannable.toString().indexOf(url);
        LogUtil.i(TAG, "url:" + url + ",index:" + index);
        if (url.startsWith("http://")) {
            if (index == -1) {
                url = url.replaceFirst("http://", "");
            }
            linkType = LINK_WEB;
        } else if (url.startsWith("https://")) {
            if (index == -1) {
                url = url.replaceFirst("https://", "");
            }
            linkType = LINK_WEB;
        } else if (url.startsWith("rtsp://")) {
            if (index == -1) {
                url = url.replaceFirst("rtsp://", "");
            }
            linkType = LINK_WEB;
        } else if (url.contains("mailto")) {
            url = url.replace("mailto:", "");
            linkType = LINK_MAIL;
        } else if (url.contains("tel")) {
            url = url.replace("tel:", "");
            linkType = LINK_TEL;
        }
        index = spannable.toString().indexOf(url);
        int end = index + url.length();
        if (index != -1) {
            spannable.removeSpan(span);
            spannable.setSpan(new UrlLinkSpan(span.getURL(), linkType), index, end,
                Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
    }
}
 
Example #20
Source Project: Indic-Keyboard   Author: smc   File: SpannableStringUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean hasUrlSpans(final CharSequence text,
        final int startIndex, final int endIndex) {
    if (!(text instanceof Spanned)) {
        return false; // Not spanned, so no link
    }
    final Spanned spanned = (Spanned)text;
    // getSpans(x, y) does not return spans that start on x or end on y. x-1, y+1 does the
    // trick, and works in all cases even if startIndex <= 0 or endIndex >= text.length().
    final URLSpan[] spans = spanned.getSpans(startIndex - 1, endIndex + 1, URLSpan.class);
    return null != spans && spans.length > 0;
}
 
Example #21
Source Project: mollyim-android   Author: mollyim   File: LinkPreviewUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return All whitelisted URLs in the source text.
 */
public static @NonNull List<Link> findWhitelistedUrls(@NonNull String text) {
  SpannableString spannable = new SpannableString(text);
  boolean         found     = Linkify.addLinks(spannable, Linkify.WEB_URLS);

  if (!found) {
    return Collections.emptyList();
  }

  return Stream.of(spannable.getSpans(0, spannable.length(), URLSpan.class))
               .map(span -> new Link(span.getURL(), spannable.getSpanStart(span)))
               .filter(link -> isWhitelistedLinkUrl(link.getUrl()))
               .toList();
}
 
Example #22
Source Project: android-discourse   Author: goodev   File: FlowTextView.java    License: Apache License 2.0 5 votes vote down vote up
private HtmlObject parseSpan(Object span, String content, int start, int end) {

        if (span instanceof URLSpan) {
            return getHtmlLink((URLSpan) span, content, start, end, 0);
        } else if (span instanceof StyleSpan) {
            return getStyledObject((StyleSpan) span, content, start, end, 0);
        } else {
            return getHtmlObject(content, start, end, 0);
        }
    }
 
Example #23
Source Project: arcusandroid   Author: arcus-smart-home   File: AccountEmailPasswordFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void stripUnderlines(@NonNull TextView tv) {
   Spannable s = (Spannable) tv.getText();
   URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);

   for (URLSpan span : spans) {
      int start = s.getSpanStart(span);
      int end = s.getSpanEnd(span);
      s.removeSpan(span);
      span = new URLSpanNoUnderline(span.getURL());
      s.setSpan(span, start, end, 0);
   }

   tv.setText(s);
}
 
Example #24
Source Project: arcusandroid   Author: arcus-smart-home   File: ViewUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void removeUnderlines(@NonNull Spannable span) {
    for (URLSpan u: span.getSpans(0, span.length(), URLSpan.class)) {
        span.setSpan(new UnderlineSpan() {
            public void updateDrawState(TextPaint tp) {
                tp.setUnderlineText(false);
            }
        }, span.getSpanStart(u), span.getSpanEnd(u), 0);
    }
}
 
Example #25
Source Project: android_9.0.0_r45   Author: lulululbj   File: TextLinks.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new TextLink.
 *
 * @param start The start index of the identified subsequence
 * @param end The end index of the identified subsequence
 * @param entityScores A mapping of entity type to confidence score
 * @param urlSpan An optional URLSpan to delegate to. NOTE: Not parcelled
 *
 * @throws IllegalArgumentException if entityScores is null or empty
 */
TextLink(int start, int end, Map<String, Float> entityScores,
        @Nullable URLSpan urlSpan) {
    Preconditions.checkNotNull(entityScores);
    Preconditions.checkArgument(!entityScores.isEmpty());
    Preconditions.checkArgument(start <= end);
    mStart = start;
    mEnd = end;
    mEntityScores = new EntityConfidence(entityScores);
    mUrlSpan = urlSpan;
}
 
Example #26
Source Project: 365browser   Author: mogoweb   File: BrowserAccessibilityManager.java    License: Apache License 2.0 5 votes vote down vote up
protected CharSequence computeText(String text, boolean annotateAsLink, String language) {
    if (annotateAsLink) {
        SpannableString spannable = new SpannableString(text);
        spannable.setSpan(new URLSpan(""), 0, spannable.length(), 0);
        return spannable;
    }
    return text;
}
 
Example #27
Source Project: android-test   Author: android   File: AccessibilityChecksIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRunAccessibilityChecks_viewWithTwoErrors() {
  // ViewAction to give view a URLSpan with an empty URL, the second accessibility error
  onView(withId(R.id.large_view))
      .perform(
          new ViewAction() {
            @Override
            public String getDescription() {
              return "Set text to include URLSpan with null url";
            }

            @Override
            public Matcher<View> getConstraints() {
              return isAssignableFrom(View.class);
            }

            @Override
            public void perform(UiController uiController, View view) {
              SpannableString spannableString = new SpannableString("Some text");
              spannableString.setSpan(new URLSpan(""), 0, 1, Spanned.SPAN_COMPOSING);
              ((TextView) view).setText(spannableString);
            }
          });
  try {
    onView(withId(R.id.large_view)).check(accessibilityAssertion());
  } catch (AccessibilityViewCheckException e) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      // Android O and above provides support for URL/ClickableSpans for accessibility
      assertEquals(1, e.getResults().size());
    } else {
      assertEquals(2, e.getResults().size());
    }
    return;
  }
  fail("Should have thrown an AccessibilityViewCheckException for a small touch target.");
}
 
Example #28
Source Project: android_9.0.0_r45   Author: lulululbj   File: AccessibilityNodeInfo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the text of this node.
 * <p>
 *   <strong>Note:</strong> Cannot be called from an
 *   {@link android.accessibilityservice.AccessibilityService}.
 *   This class is made immutable before being delivered to an AccessibilityService.
 * </p>
 *
 * @param text The text.
 *
 * @throws IllegalStateException If called from an AccessibilityService.
 */
public void setText(CharSequence text) {
    enforceNotSealed();
    mOriginalText = text;
    // Replace any ClickableSpans in mText with placeholders
    if (text instanceof Spanned) {
        ClickableSpan[] spans =
                ((Spanned) text).getSpans(0, text.length(), ClickableSpan.class);
        if (spans.length > 0) {
            Spannable spannable = new SpannableStringBuilder(text);
            for (int i = 0; i < spans.length; i++) {
                ClickableSpan span = spans[i];
                if ((span instanceof AccessibilityClickableSpan)
                        || (span instanceof AccessibilityURLSpan)) {
                    // We've already done enough
                    break;
                }
                int spanToReplaceStart = spannable.getSpanStart(span);
                int spanToReplaceEnd = spannable.getSpanEnd(span);
                int spanToReplaceFlags = spannable.getSpanFlags(span);
                spannable.removeSpan(span);
                ClickableSpan replacementSpan = (span instanceof URLSpan)
                        ? new AccessibilityURLSpan((URLSpan) span)
                        : new AccessibilityClickableSpan(span.getId());
                spannable.setSpan(replacementSpan, spanToReplaceStart, spanToReplaceEnd,
                        spanToReplaceFlags);
            }
            mText = spannable;
            return;
        }
    }
    mText = (text == null) ? null : text.subSequence(0, text.length());
}
 
Example #29
Source Project: android_9.0.0_r45   Author: lulululbj   File: Html.java    License: Apache License 2.0 5 votes vote down vote up
private static void endA(Editable text) {
    Href h = getLast(text, Href.class);
    if (h != null) {
        if (h.mHref != null) {
            setSpanFromMark(text, h, new URLSpan((h.mHref)));
        }
    }
}
 
Example #30
Source Project: datmusic-android   Author: alashow   File: U.java    License: Apache License 2.0 5 votes vote down vote up
public static void stripUnderlines(TextView textView) {
    Spannable s = (Spannable) textView.getText();
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for(URLSpan span : spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);
        span = new URLSpanNoUnderline(span.getURL());
        s.setSpan(span, start, end, 0);
    }
    textView.setText(s);
}