/** * @param context * @param spannable * @param title * @return */ public static SpannableStringBuilder getText(Activity context, Spannable spannable, String title) { if (spannable == null || spannable.length() <= 0) { Log.e(TAG, "getText spannable == null || spannable.length() <= 0 >> return new SpannableStringBuilder();"); return new SpannableStringBuilder(); } SpannableStringBuilder builder = new SpannableStringBuilder(spannable); builder.clearSpans();// should clear old spans URLSpan[] urls = spannable.getSpans(0, spannable.length(), URLSpan.class); if (urls != null) { for (URLSpan urlSpan : urls) { if (urlSpan != null) { MyURLSpan myURLSpan = new MyURLSpan(context, urlSpan.getURL(), title); builder.setSpan(myURLSpan, spannable.getSpanStart(urlSpan), spannable .getSpanEnd(urlSpan), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } } } return builder; }
/** * Taken from Stack Overflow - https://stackoverflow.com/a/17201376/6052295 * Adds links to a HTML string * * @param html the HTML string to add links to * @param linkifyMask the link type * @return The spannable text with clickable links */ public static Spannable linkifyHtml(String html, int linkifyMask) { Spanned text = fromHtml(fromHtml(html).toString()); URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class); SpannableString buffer = new SpannableString(text); Linkify.addLinks(buffer, linkifyMask); for (URLSpan span : currentSpans) { int end = text.getSpanEnd(span); int start = text.getSpanStart(span); buffer.setSpan(span, start, end, 0); } return buffer; }
/** * 解析link * * @param tv_content * @param context */ private static void dealUnderLinesData(TextView tv_content, Context context) { CharSequence charSequence = tv_content.getText(); if (charSequence instanceof Spannable) { tv_content.setText(""); Spannable s = EmojiDisplay.spannableFilter(tv_content.getContext(), new SpannableStringBuilder(charSequence), charSequence, EmoticonsKeyboardUtils.getFontHeight(tv_content)); URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); for (URLSpan span : spans) { int start = s.getSpanStart(span); int end = s.getSpanEnd(span); String clickText = s.subSequence(start, end).toString(); URLSpanNoUnderline urlSpanNoUnderline = new URLSpanNoUnderline(context, span.getURL(), clickText); s.setSpan(urlSpanNoUnderline, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } tv_content.append(s); } }
/** * 解析机器人对话link * * @param textView */ private static void dealAILink(TextView textView, String type) { CharSequence charSequence = textView.getText(); if (charSequence instanceof Spannable) { textView.setText(""); Spannable s = (Spannable) charSequence; URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); for (URLSpan span : spans) { int start = s.getSpanStart(span); int end = s.getSpanEnd(span); String clickContent = s.subSequence(start, end).toString(); AIURLSpan myURLSpan = new AIURLSpan(span.getURL(), type, clickContent, textView.getContext()); s.setSpan(myURLSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } textView.append(s); } }
/** * 解析富文本link * * @param textView */ private static void dealCustomLink(TextView textView) { CharSequence charSequence = textView.getText(); if (charSequence instanceof Spannable) { textView.setText(""); Spannable s = (Spannable) charSequence; URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); for (URLSpan span : spans) { int start = s.getSpanStart(span); int end = s.getSpanEnd(span); CustomClickSpan myURLSpan = new CustomClickSpan(textView.getContext(), span.getURL()); s.setSpan(myURLSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } textView.append(s); } }
@Override protected void onLongPress() { if (pressedLink instanceof URLSpanNoUnderline) { URLSpanNoUnderline url = (URLSpanNoUnderline) pressedLink; if (url.getURL().startsWith("/")) { delegate.didPressedUrl(currentMessageObject, pressedLink, true); return; } } else if (pressedLink instanceof URLSpan) { delegate.didPressedUrl(currentMessageObject, pressedLink, true); return; } resetPressedLink(-1); if (buttonPressed != 0 || pressedBotButton != -1) { buttonPressed = 0; pressedBotButton = -1; invalidate(); } if (delegate != null) { delegate.didLongPressed(this); } }
public static void makeLinksClickable(TextView v) { SpannableStringBuilder ssb = new SpannableStringBuilder(v.getText()); URLSpan[] spans = ssb.getSpans(0, ssb.length(), URLSpan.class); for (URLSpan span : spans) { int start = ssb.getSpanStart(span); int end = ssb.getSpanEnd(span); final String url = span.getURL(); ssb.removeSpan(span); ClickableSpan cSpan = new ClickableSpan() { @Override public void onClick(View v2) { LinkDialogFragment f = LinkDialogFragment.newInstance(url); FragmentManager fm = ((AppCompatActivity) v2.getContext()) .getSupportFragmentManager(); f.show(fm, f.getUniqueTag()); } }; ssb.setSpan(cSpan, start, end, 0); } v.setText(ssb); v.setMovementMethod(ArticleMovementMethod.getInstance()); }
public OrgSpannable(String str) { SpannableStringBuilder ssb = OrgFormatter.INSTANCE.parse(context, str); string = ssb.toString(); Object[] allSpans = ssb.getSpans(0, ssb.length() - 1, Object.class); spans = new OrgSpan[allSpans.length]; for (int i = 0; i < allSpans.length; i++) { spans[i] = new OrgSpan(); spans[i].start = ssb.getSpanStart(allSpans[i]); spans[i].end = ssb.getSpanEnd(allSpans[i]); spans[i].className = allSpans[i].getClass().getSimpleName(); if (allSpans[i] instanceof URLSpan) { spans[i].url = ((URLSpan)allSpans[i]).getURL(); } } }
private void setHtmlFromHelpFile(String file) { htmltv.setHtml(getHelpFileContents(file)); htmltv.setText(RichTextUtils.replaceAll((Spanned) htmltv.getText(), URLSpan.class, new RichTextUtils.URLSpanConverter(), new RichTextUtils.ClickSpan.OnClickListener() { @Override public void onClick(String url) { if(mListener == null) { return; } if (url.startsWith("help:")) { mListener.onHelpLinkClicked(url.substring(5)); } else if (url.startsWith("station:")) { mListener.onStationLinkClicked(url.substring(8)); } else if (url.startsWith("mailto:")) { mListener.onMailtoLinkClicked(url.substring(7)); } else { mListener.onLinkClicked(url); } } })); }
public static void setHtmlWithLinkClickHandler(TextView tv, String html, Action1<String> linkClickHandler) { CharSequence sequence = Html.fromHtml(html); SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence); URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class); for (URLSpan span : urls) { int start = strBuilder.getSpanStart(span); int end = strBuilder.getSpanEnd(span); int flags = strBuilder.getSpanFlags(span); ClickableSpan clickable = new ClickableSpan() { public void onClick(View view) { linkClickHandler.call(span.getURL()); } }; strBuilder.setSpan(clickable, start, end, flags); strBuilder.removeSpan(span); } tv.setText(strBuilder); tv.setMovementMethod(LinkMovementMethod.getInstance()); }
private void setApplication(@Nullable Status.Application app) { if (app != null) { timestampInfo.append(" • "); if (app.website != null) { URLSpan span = new CustomURLSpan(app.website); SpannableStringBuilder text = new SpannableStringBuilder(app.name); text.setSpan(span, 0, app.name.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); timestampInfo.append(text); timestampInfo.setMovementMethod(LinkMovementMethod.getInstance()); } else { timestampInfo.append(app.name); } } }
private void onUploadSuccess(final QueuedMedia item, Attachment media) { item.id = media.id; item.preview.setProgress(-1); item.readyStage = QueuedMedia.ReadyStage.UPLOADED; /* Add the upload URL to the text field. Also, keep a reference to the span so if the user * chooses to remove the media, the URL is also automatically removed. */ item.uploadUrl = new URLSpan(media.textUrl); int end = 1 + media.textUrl.length(); SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(' '); builder.append(media.textUrl); builder.setSpan(item.uploadUrl, 1, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); int cursorStart = textEditor.getSelectionStart(); int cursorEnd = textEditor.getSelectionEnd(); textEditor.append(builder); textEditor.setSelection(cursorStart, cursorEnd); waitForMediaLatch.countDown(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_invite_friends); ButterKnife.bind(this); Intent intent = getIntent(); String addresseeName = intent.getStringExtra("contactName"); addresseePhone = intent.getStringExtra("contactPhone"); mAddresseeName.setText(addresseeName); SpannableString inviteMessage = new SpannableString(this.getResources().getString(R.string.mine_send_message)); message = this.getResources().getString(R.string.mine_send_message); inviteMessage.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 54, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); inviteMessage.setSpan(new URLSpan("http://www.xingka.cc"), 54, 74,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); inviteMessage.setSpan(new ForegroundColorSpan(Color.BLACK), 74, 88, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); mInviteMessage.setText(inviteMessage); mInviteMessage.setMovementMethod(LinkMovementMethod.getInstance()); }
public static void convertToLinkSpan(Context context, TextView textView) { Spannable s = new SpannableString(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 LinkSpan(context, span.getURL()); s.setSpan(span, start, end, 0); } textView.setText(s); }
@Override public CharSequence getTransformation(CharSequence src, View view) { if (view instanceof TextView) { TextView textView = (TextView) view; Linkify.addLinks(textView, Linkify.WEB_URLS); if (textView.getText() != null && textView.getText() instanceof Spannable) { Spannable text = (Spannable) textView.getText(); URLSpan[] spans = text.getSpans(0, textView.length(), URLSpan.class); for (int i = spans.length - 1; i >= 0; i--) { URLSpan oldSpan = spans[i]; int start = text.getSpanStart(oldSpan), end = text.getSpanEnd(oldSpan); String url = oldSpan.getURL(); text.removeSpan(oldSpan); text.setSpan(new CustomTabsURLSpan(url), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return text; } } return src; }
@Override public boolean onSingleTapConfirmed(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); x -= textView.getTotalPaddingLeft(); y -= textView.getTotalPaddingTop(); x += textView.getScrollX(); y += textView.getScrollY(); Layout layout = textView.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); URLSpan[] link = buffer.getSpans(off, off, URLSpan.class); if (link.length > 0) { String linkText = link[0].getURL(); if (Patterns.WEB_URL.matcher(linkText).matches()) CustomTabsBuilder.open(context, Uri.parse(linkText)); return true; } return false; }
public static CharSequence replaceURLSpans(CharSequence text) { if (text instanceof Spannable) { final Spannable s = (Spannable) text; final URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); if (spans != null && spans.length > 0) { for (int i = spans.length - 1; i >= 0; i--) { final URLSpan span = spans[i]; final int start = s.getSpanStart(span); final int end = s.getSpanEnd(span); final int flags = s.getSpanFlags(span); s.removeSpan(span); s.setSpan(new SafeURLSpan(span.getURL()), start, end, flags); } } } return text; }
private void makeLinkClickable(SpannableStringBuilder strBuilder, URLSpan span) { final String url = span.getURL(); /* http://stackoverflow.com/a/19989677/1726690 */ int start = strBuilder.getSpanStart(span); int end = strBuilder.getSpanEnd(span); int flags = strBuilder.getSpanFlags(span); ClickableSpan clickable = new ClickableSpan() { public void onClick(View view) { if ((!onLinkClicked(url)) && (mLinkListener != null)) { mLinkListener.onLinkClick(url); } } }; strBuilder.setSpan(clickable, start, end, flags); strBuilder.removeSpan(span); }
private String findFeaturedArticleTitle(String pageLeadContent) { // Extract the actual link to the featured page in a hacky way (until we // have the correct API for it): // Parse the HTML, and look for the first link, which should be the // article of the day. Spanned text = Html.fromHtml(pageLeadContent); URLSpan[] spans = text.getSpans(0, text.length(), URLSpan.class); String titleText = ""; for (URLSpan span : spans) { if (!span.getURL().startsWith("/wiki/") || (text.getSpanEnd(span) - text.getSpanStart(span) <= 1)) { continue; } PageTitle title = WikipediaApp.getInstance().getPrimarySite() .titleForInternalLink(decodeURL(span.getURL())); if (!title.isFilePage() && !title.isSpecial()) { titleText = title.getDisplayText(); break; } } return titleText; }
@Override public boolean onTouchEvent(@NonNull final TextView widget, @NonNull final Spannable buffer, @NonNull final MotionEvent event) { final int action = event.getAction(); if (action == MotionEvent.ACTION_UP) { final int x = (int) event.getX() - widget.getTotalPaddingLeft() + widget.getScrollX(); final int y = (int) event.getY() - widget.getTotalPaddingTop() + widget.getScrollY(); final Layout layout = widget.getLayout(); final int line = layout.getLineForVertical(y); final int off = layout.getOffsetForHorizontal(line, x); final URLSpan[] links = buffer.getSpans(off, off, URLSpan.class); if (links.length != 0) { String url = decodeURL(links[0].getURL()); handler.onUrlClick(url); return true; } } return super.onTouchEvent(widget, buffer, event); }
public static Spanned convertUrlSpanToCustomTabs(Spanned spanned, Context context){ SpannableStringBuilder builder = new SpannableStringBuilder(spanned); URLSpan[] spans = spanned.getSpans(0, spanned.length(), URLSpan.class); for (URLSpan span : spans) { builder.removeSpan(span); builder.setSpan(new ClickableSpan() { @Override public void onClick(View view) { new CustomTabsIntent.Builder() .setToolbarColor(ContextCompat.getColor(context, R.color.colorPrimary)) .setSecondaryToolbarColor(ContextCompat.getColor(context, R.color.colorPrimaryDark)) .addDefaultShareMenuItem() .build() .launchUrl(context, Uri.parse(span.getURL())); } }, spanned.getSpanStart(span), spanned.getSpanEnd(span), spanned.getSpanFlags(span)); } return builder; }
public static 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) { // Do something with span.getURL() to handle the link click... /*if (span.getURL().startsWith("baseURL")) { //TODO stay in app } else */ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(span.getURL())); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //running from 'outside' and activity view.getContext().getApplicationContext().startActivity(intent); } }; strBuilder.setSpan(clickable, start, end, flags); strBuilder.removeSpan(span); }
/** * 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; }
private static void setLinkClickable(Context context, final SpannableStringBuilder clickableHtmlBuilder, final URLSpan urlSpan, String sourceUrl) { int start = clickableHtmlBuilder.getSpanStart(urlSpan); int end = clickableHtmlBuilder.getSpanEnd(urlSpan); int flags = clickableHtmlBuilder.getSpanFlags(urlSpan); ClickableSpan clickableSpan = new ClickableSpan() { public void onClick(View view) { Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); String url = urlSpan.getURL(); url = TextUtils.isEmpty(url) ? "" : RegexValidateUtil.getAbsoluteUrlFromRelative(url, sourceUrl); intent.setData(Uri.parse(url)); context.startActivity(intent); } }; clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags); }
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>"); } }
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); } } }
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); }
private CharSequence getPostFloor() { Post p = post.get(); if (p == null) { return null; } String text = "#" + p.getCount(); Spannable spannable = new SpannableString(text); URLSpan urlSpan = new URLSpan(StringUtils.EMPTY) { @Override public void onClick(@NonNull View widget) { showFloorActionMenu(widget); } }; spannable.setSpan(urlSpan, 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return spannable; }
private static SpannableStringBuilder linkifyPlainLinks(CharSequence input, ColorStateList linkTextColor, @ColorInt int linkHighlightColor) { final SpannableString plainLinks = new SpannableString(input); // copy of input 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.setSpan(new TouchableUrlSpan(urlSpan.getURL(), linkTextColor, linkHighlightColor), plainLinks.getSpanStart(urlSpan), plainLinks.getSpanEnd(urlSpan), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return ssb; }
private Spannable formatForTextView(Spannable p_Text) { URLSpan[] spans = p_Text.getSpans(0, p_Text.length(), URLSpan.class); Pattern hashTagURLPattern = Pattern.compile(".*\\/\\#tags\\/.*", Pattern.CASE_INSENSITIVE); Matcher hashtagMatcher = null; for (URLSpan span : spans) { hashtagMatcher = hashTagURLPattern.matcher(span.getURL()); // Only format if it's a hashtag link if (hashtagMatcher.find()) { int start = p_Text.getSpanStart(span); int end = p_Text.getSpanEnd(span); p_Text.removeSpan(span); span = new URLSpanNoUnderline(span.getURL()); p_Text.setSpan(span, start, end, 0); } } return p_Text; }
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 == null) { Log.e("endA", "h = null"); return; } if (h.mHref != null) { text.setSpan(new URLSpan(h.mHref), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } }
private SpannableString wrapIntoHashGirlURLSpan(String htmlText, final OnClickHashListener onClickHashListener) { SpannableString s = SpannableString.valueOf(Html.fromHtml(htmlText)); URLSpan[] urlSpanList = s.getSpans(0, s.length(), URLSpan.class); for(URLSpan urlSpan : urlSpanList) { int start = s.getSpanStart(urlSpan); int end = s.getSpanEnd(urlSpan); s.removeSpan(urlSpan); HashGirlURLSpan hashGirlURLSpan = new HashGirlURLSpan(urlSpan.getURL(), new OnClickHashListener() { @Override public void onClickHash(String url) { if(onClickHashListener != null) { onClickHashListener.onClickHash(url); } } }); hashGirlURLSpan.setUnderline(underline); hashGirlURLSpan.setStrike(strike); hashGirlURLSpan.setColor(color); hashGirlURLSpan.setBgcolor(bgcolor); hashGirlURLSpan.setAlpha(alpha); s.setSpan(hashGirlURLSpan, start, end, 0); } return s; }