android.text.Spannable Java Examples
The following examples show how to use
android.text.Spannable.
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 File: GoURLSpan.java From droidddle with Apache License 2.0 | 6 votes |
/** * @param spanText * @return true if have url */ public static final boolean hackURLSpanHasResult(SpannableStringBuilder spanText) { boolean result = false; URLSpan[] spans = spanText.getSpans(0, spanText.length(), URLSpan.class); // TODO URLSpan need change to ClickableSpan (GoURLSpan) , otherwise URLSpan can not click, not display underline.WHY? for (URLSpan span : spans) { int start = spanText.getSpanStart(span); int end = spanText.getSpanEnd(span); String url = span.getURL(); if (url != null) { result = true; spanText.removeSpan(span); ClickableSpan span1 = new GoURLSpan(span.getURL()); spanText.setSpan(span1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } return result; }
Example #2
Source File: CheckForNewMessages.java From SteamGifts with MIT License | 6 votes |
/** * Returns the comment's content, and, optionally, the author's name * * @param comment comment to display the content of * @param includeName whether or not to include the author's name * @return text to display in the notification */ @NonNull private CharSequence formatComment(Comment comment, boolean includeName) { String content = StringUtils.fromHtml(context, comment.getContent()).toString(); if (TextUtils.isEmpty(content) && comment.getAttachedImages() != null && comment.getAttachedImages().size() > 0) { content = context.getString(R.string.notification_has_attached_image); } if (includeName && comment.getAuthor() != null) { SpannableString sb = new SpannableString(String.format("%s %s", comment.getAuthor(), content)); sb.setSpan(new StyleSpan(Typeface.BOLD), 0, comment.getAuthor().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return sb; } else { return content; } }
Example #3
Source File: WizardPage2Activity.java From secure-quick-reliable-login with MIT License | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Utils.setLanguage(this); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.startup_wizard_page_2); TextView wizardText = findViewById(R.id.wizard_text); String s = (String)wizardText.getText(); Spannable textSpan = Utils.getSpanWithHighlight(s); wizardText.setText(textSpan); Button next = findViewById(R.id.wizard_next); next.setOnClickListener((a) -> { startActivity(new Intent(this, WizardPage3Activity.class)); }); Button skip = findViewById(R.id.wizard_skip); skip.setOnClickListener((a) -> { startActivity(new Intent(this, StartActivity.class)); }); }
Example #4
Source File: ArrowKeyMovementMethod.java From JotaTextEditor with Apache License 2.0 | 6 votes |
private boolean down(TextView widget, Spannable buffer) { boolean cap = (MetaKeyKeyListener.getMetaState(buffer, KeyEvent.META_SHIFT_ON) == 1) || (JotaTextKeyListener.getMetaStateSelecting(buffer) != 0); boolean alt = MetaKeyKeyListener.getMetaState(buffer, KeyEvent.META_ALT_ON) == 1; Layout layout = widget.getLayout(); if (cap) { if (alt) { // Selection.extendSelection(buffer, buffer.length()); widget.movePage(false,true); return true; } else { return Selection.extendDown(buffer, layout); } } else { if (alt) { // Selection.setSelection(buffer, buffer.length()); widget.movePage(false,false); return true; } else { return Selection.moveDown(buffer, layout); } } }
Example #5
Source File: CensoredTextHolderEx.java From actor-platform with GNU Affero General Public License v3.0 | 6 votes |
@Override public void bindRawText(CharSequence rawText, long readDate, long receiveDate, Spannable reactions, Message message, boolean isItalic) { Spannable res = new SpannableString(rawText); for (String s : badWords) { // rawText = rawText.toString().replaceAll("/*(?i)" + s + "/*", new String(new char[s.length()]).replace('\0', '*')); Pattern p = Pattern.compile("/*(?i)" + s + "/*"); Matcher m = p.matcher(rawText.toString()); while (m.find()) { CensorSpan span = new CensorSpan(); res.setSpan(span, m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } super.bindRawText(res, readDate, receiveDate, reactions, message, isItalic); }
Example #6
Source File: ArrowKeyMovementMethod.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
@Override protected boolean pageDown(TextView widget, Spannable buffer) { final Layout layout = widget.getLayout(); final boolean selecting = isSelecting(buffer); final int targetY = getCurrentLineTop(buffer, layout) + getPageHeight(widget); boolean handled = false; for (;;) { final int previousSelectionEnd = Selection.getSelectionEnd(buffer); if (selecting) { Selection.extendDown(buffer, layout); } else { Selection.moveDown(buffer, layout); } if (Selection.getSelectionEnd(buffer) == previousSelectionEnd) { break; } handled = true; if (getCurrentLineTop(buffer, layout) >= targetY) { break; } } return handled; }
Example #7
Source File: QiscusBaseImageMessageViewHolder.java From qiscus-sdk-android with Apache License 2.0 | 6 votes |
protected void showCaption(QiscusComment qiscusComment) { if (captionView != null) { captionView.setVisibility(TextUtils.isEmpty(qiscusComment.getCaption()) ? View.GONE : View.VISIBLE); QiscusMentionConfig mentionConfig = Qiscus.getChatConfig().getMentionConfig(); if (mentionConfig.isEnableMention()) { Spannable spannable = QiscusTextUtil.createQiscusSpannableText( qiscusComment.getCaption(), roomMembers, messageFromMe ? mentionConfig.getRightMentionAllColor() : mentionConfig.getLeftMentionAllColor(), messageFromMe ? mentionConfig.getRightMentionOtherColor() : mentionConfig.getLeftMentionOtherColor(), messageFromMe ? mentionConfig.getRightMentionMeColor() : mentionConfig.getLeftMentionMeColor(), mentionConfig.getMentionClickHandler() ); captionView.setText(spannable); } else { captionView.setText(qiscusComment.getCaption()); } } }
Example #8
Source File: RTEditText.java From memoir with Apache License 2.0 | 6 votes |
/** * Call this to have an effect applied to the current selection. * You get the Effect object via the static data members (e.g., RTEditText.BOLD). * The value for most effects is a Boolean, indicating whether to add or remove the effect. */ public <V extends Object, C extends RTSpan<V>> void applyEffect(Effect<V, C> effect, V value) { if (mUseRTFormatting && !mIsSelectionChanging && !mIsSaving) { Spannable oldSpannable = mIgnoreTextChanges ? null : cloneSpannable(); effect.applyToSelection(this, value); synchronized (this) { if (mListener != null && !mIgnoreTextChanges) { Spannable newSpannable = cloneSpannable(); mListener.onTextChanged(this, oldSpannable, newSpannable, getSelectionStart(), getSelectionEnd(), getSelectionStart(), getSelectionEnd()); } mLayoutChanged = true; } } }
Example #9
Source File: QBMessageTextClickMovement.java From ChatMessagesAdapter-android with BSD 3-Clause "New" or "Revised" License | 6 votes |
private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent 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); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { return buffer.subSequence(buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])).toString(); } return buffer.toString(); }
Example #10
Source File: RTEditorMovementMethod.java From Android-RTEditor with Apache License 2.0 | 6 votes |
@Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int index = getCharIndexAt(widget, event); if (index != -1) { ClickableSpan[] link = buffer.getSpans(index, index, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget); } else if (action == MotionEvent.ACTION_DOWN) { Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); } return true; } } /*else { Selection.removeSelection(buffer); }*/ } return super.onTouchEvent(widget, buffer, event); }
Example #11
Source File: ComposeText.java From deltachat-android with GNU General Public License v3.0 | 6 votes |
public void setHint(@NonNull String hint, @Nullable CharSequence subHint) { this.hint = hint; if (subHint != null) { this.subHint = new SpannableString(subHint); this.subHint.setSpan(new RelativeSizeSpan(0.5f), 0, subHint.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); } else { this.subHint = null; } if (this.subHint != null) { super.setHint(new SpannableStringBuilder().append(ellipsizeToWidth(this.hint)) .append("\n") .append(ellipsizeToWidth(this.subHint))); } else { super.setHint(ellipsizeToWidth(this.hint)); } }
Example #12
Source File: RecipientEditTextView.java From ChipsLibrary with Apache License 2.0 | 6 votes |
DrawableRecipientChip[] getSortedRecipients() { final DrawableRecipientChip[] recips=getSpannable().getSpans(0,getText().length(),DrawableRecipientChip.class); final ArrayList<DrawableRecipientChip> recipientsList=new ArrayList<DrawableRecipientChip>(Arrays.asList(recips)); final Spannable spannable=getSpannable(); Collections.sort(recipientsList,new Comparator<DrawableRecipientChip>() { @Override public int compare(final DrawableRecipientChip first,final DrawableRecipientChip second) { final int firstStart=spannable.getSpanStart(first); final int secondStart=spannable.getSpanStart(second); if(firstStart<secondStart) return -1; else if(firstStart>secondStart) return 1; else return 0; } }); return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]); }
Example #13
Source File: LongClickableLinkMovementMethod.java From RichEditor with MIT License | 6 votes |
private BlockImageSpan getPressedSpan(TextView textView, Spannable spannable, MotionEvent event) { int x = (int) event.getX() - textView.getTotalPaddingLeft() + textView.getScrollX(); int y = (int) event.getY() - textView.getTotalPaddingTop() + textView.getScrollY(); Layout layout = textView.getLayout(); int position = layout.getOffsetForHorizontal(layout.getLineForVertical(y), x); BlockImageSpan[] blockImageSpans = spannable.getSpans(position, position, BlockImageSpan.class); BlockImageSpan touchedSpan = null; if (blockImageSpans.length > 0 && positionWithinTag(position, spannable, blockImageSpans[0]) && blockImageSpans[0].clicked(x, y)) { touchedSpan = blockImageSpans[0]; } return touchedSpan; }
Example #14
Source File: TextViewLinkHandler.java From Slide with GNU General Public License v3.0 | 6 votes |
public TextViewLinkHandler(ClickableText clickableText, String subreddit, Spannable sequence) { this.clickableText = clickableText; this.subreddit = subreddit; this.sequence = sequence; clickHandled = false; handler = new Handler(); longClicked = new Runnable() { @Override public void run() { // long click clickHandled = true; handler.removeCallbacksAndMessages(null); if (link != null && link.length > 0 && link[0] != null) { TextViewLinkHandler.this.clickableText.onLinkLongClick(link[0].getURL(), event); } } }; }
Example #15
Source File: PayerCostFormatter.java From px-android with MIT License | 6 votes |
public Spannable apply() { Spannable totalAmount = new SpannableStringBuilder(); if (payerCost.getInstallments() > 1) { totalAmount = TextFormatter.withCurrency(currency) .amount(payerCost.getTotalAmount()) .normalDecimals() .apply(R.string.px_total_amount_holder, context); } final int initialIndex = spannableStringBuilder.length(); final String separator = " "; spannableStringBuilder.append(separator).append(totalAmount); final int textLength = separator.length() + totalAmount.length(); final int endIndex = initialIndex + textLength; ViewUtils.setColorInSpannable(textColor, initialIndex, endIndex, spannableStringBuilder); ViewUtils.setFontInSpannable(context, PxFont.REGULAR, spannableStringBuilder, initialIndex, endIndex); return spannableStringBuilder; }
Example #16
Source File: CustomHtmlToSpannedConverter.java From zulip-android with Apache License 2.0 | 6 votes |
private static void endHeader(SpannableStringBuilder text) { int len = text.length(); Object obj = getLast(text, Header.class); int where = text.getSpanStart(obj); text.removeSpan(obj); // Back off not to change only the text, not the blank line. while (len > where && text.charAt(len - 1) == '\n') { len--; } if (where != len) { Header h = (Header) obj; text.setSpan(new RelativeSizeSpan(HEADER_SIZES[h.mLevel]), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); text.setSpan(new StyleSpan(Typeface.BOLD), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } }
Example #17
Source File: CommentsAdapter.java From mentions with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Highlights all the {@link Mentionable}s in the test {@link Comment}. */ private void highlightMentions(final TextView commentTextView, final List<Mentionable> mentions) { if(commentTextView != null && mentions != null && !mentions.isEmpty()) { final Spannable spannable = new SpannableString(commentTextView.getText()); for (Mentionable mention: mentions) { if (mention != null) { final int start = mention.getMentionOffset(); final int end = start + mention.getMentionLength(); if (commentTextView.length() >= end) { spannable.setSpan(new ForegroundColorSpan(orange), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); commentTextView.setText(spannable, TextView.BufferType.SPANNABLE); } else { //Something went wrong. The expected text that we're trying to highlight does not // match the actual text at that position. Log.w("Mentions Sample", "Mention lost. [" + mention + "]"); } } } } }
Example #18
Source File: Logger.java From nfcspy with GNU General Public License v3.0 | 5 votes |
static CharSequence fmt(int colorResId, CharSequence msg) { final int color = ThisApplication.getColorResource(colorResId); final SpannableString ret = new SpannableString(msg); final ForegroundColorSpan span = new ForegroundColorSpan(color); ret.setSpan(span, 0, msg.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); return ret; }
Example #19
Source File: HiHtmlTagHandler.java From hipda with GNU General Public License v2.0 | 5 votes |
private void processAppmark(boolean opening, Editable output) { int len = output.length(); if (opening) { output.setSpan(new RelativeSizeSpan(0.75f), len, len, Spannable.SPAN_MARK_MARK); } else { Object obj = getLast(output, RelativeSizeSpan.class); int where = output.getSpanStart(obj); output.removeSpan(obj); if (where != len) { output.setSpan(new RelativeSizeSpan(0.75f), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } }
Example #20
Source File: EaseChatRowText.java From Study_Android_Demo with Apache License 2.0 | 5 votes |
@Override public void onSetUpView() { EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody(); Spannable span = EaseSmileUtils.getSmiledText(context, txtBody.getMessage()); // 设置内容 contentView.setText(span, BufferType.SPANNABLE); handleTextMessage(); }
Example #21
Source File: KnifeTagHandler.java From Knife with Apache License 2.0 | 5 votes |
private static Object getLast(Editable text, Class kind) { Object[] spans = text.getSpans(0, text.length(), kind); if (spans.length == 0) { return null; } else { for (int i = spans.length; i > 0; i--) { if (text.getSpanFlags(spans[i - 1]) == Spannable.SPAN_MARK_MARK) { return spans[i - 1]; } } return null; } }
Example #22
Source File: MessagesListAdapter.java From ChatKit with Apache License 2.0 | 5 votes |
protected void configureLinksBehavior(final TextView text) { text.setLinksClickable(false); text.setMovementMethod(new LinkMovementMethod() { @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { boolean result = false; if (!isSelectionModeEnabled) { result = super.onTouchEvent(widget, buffer, event); } itemView.onTouchEvent(event); return result; } }); }
Example #23
Source File: SuggestionsWidget.java From FirefoxReality with Mozilla Public License 2.0 | 5 votes |
private SpannableStringBuilder createHighlightedText(@NonNull String text) { final SpannableStringBuilder sb = new SpannableStringBuilder(text); final StyleSpan bold = new StyleSpan(Typeface.BOLD); final StyleSpan normal = new StyleSpan(Typeface.NORMAL); int start = text.toLowerCase().indexOf(mHighlightedText.toLowerCase()); if (start >= 0) { int end = start + mHighlightedText.length(); sb.setSpan(normal, 0, start, Spannable.SPAN_INCLUSIVE_INCLUSIVE); sb.setSpan(bold, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); sb.setSpan(normal, end, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); } return sb; }
Example #24
Source File: RichEditText.java From o2oa with GNU Affero General Public License v3.0 | 5 votes |
public static Spannable matchMention(Spannable spannable) { String text = spannable.toString(); Pattern pattern = Pattern.compile(MATCH_MENTION); Matcher matcher = pattern.matcher(text); while (matcher.find()) { String str = matcher.group(); int matcherStart = matcher.start(); int matcherEnd = matcher.end(); spannable.setSpan(new TagSpan(str), matcherStart, matcherEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); log("matchMention:" + str + " " + matcherStart + " " + matcherEnd); } return spannable; }
Example #25
Source File: Trestle.java From Trestle with Apache License 2.0 | 5 votes |
private static void setUpAbsoluteSizeSpan(Span span, SpannableString ss, int start, int end) { int absoluteSize = span.getAbsoluteSize(); if (absoluteSize != 0) { ss.setSpan( new AbsoluteSizeSpan(absoluteSize, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } }
Example #26
Source File: WindowViewModel.java From FirefoxReality with Mozilla Public License 2.0 | 5 votes |
@Override public void onChanged(Spannable aUrl) { String url = aUrl.toString(); if (isBookmarksVisible.getValue().get()) { url = getApplication().getString(R.string.url_bookmarks_title); } else if (isHistoryVisible.getValue().get()) { url = getApplication().getString(R.string.url_history_title); } else if (isDownloadsVisible.getValue().get()) { url = getApplication().getString(R.string.url_downloads_title); } else { if (UrlUtils.isPrivateAboutPage(getApplication(), url) || (UrlUtils.isDataUri(url) && isPrivateSession.getValue().get())) { url = getApplication().getString(R.string.private_browsing_title); } else if (UrlUtils.isHomeUri(getApplication(), aUrl.toString())) { url = getApplication().getString(R.string.url_home_title, getApplication().getString(R.string.app_name)); } else if (UrlUtils.isBlankUri(getApplication(), aUrl.toString())) { url = ""; } } titleBarUrl.postValue(UrlUtils.titleBarUrl(url)); }
Example #27
Source File: ChatActivity.java From emoji with Apache License 2.0 | 5 votes |
@Override public void onEmoticonTap(String drawableId) { Editable editable = mChatEditorTxt.getText(); int index = mChatEditorTxt.getSelectionEnd(); String emo = EmojiParser.getInstance(this).convertToUnicode(drawableId); SpannableStringBuilder builder = new SpannableStringBuilder(emo); int resId = getResources().getIdentifier("emoji_" + drawableId, "drawable", getPackageName()); Drawable d = getResources().getDrawable(resId); d.setBounds(0, 0, 30, 30); ImageSpan span = new ImageSpan(d); builder.setSpan(span, 0, emo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (index < mChatEditorTxt.length()) { editable.insert(index, builder); }else { editable.append(builder); } mChatEditorTxt.setSelection(index + emo.length()); // drawableSrc = "emoji_" + drawableId; // ImageGetter imageGetter = new ImageGetter() { // public Drawable getDrawable(String source) { // int id = ChatActivity.this.getResources().getIdentifier(source, "drawable", getPackageName()); // Drawable d = ChatActivity.this.getResources().getDrawable(id); // d.setBounds(0, 0, 24, 24); // return d; // } // }; // CharSequence cs1 = Html.fromHtml("<img src='" + drawableSrc + "'/>", imageGetter, null); // int index = mChatEditorTxt.getSelectionStart(); // Editable etb = mChatEditorTxt.getText(); // int length = etb.length(); // if (index < length) { // etb.insert(index, cs1); // } else { // mChatEditorTxt.append(cs1); // } // mChatEditorTxt.setSelection(index + 1); }
Example #28
Source File: SyncDetailCalculations.java From commcare-android with Apache License 2.0 | 5 votes |
public static void updateSubText(final StandardHomeActivity activity, SquareButtonViewHolder squareButtonViewHolder, HomeCardDisplayData cardDisplayData, String notificationText) { int numUnsentForms = getNumUnsentForms(); Pair<Long, String> lastSyncTimeAndMessage = getLastSyncTimeAndMessage(); Spannable syncIndicator = (activity.localize("home.unsent.forms.indicator", new String[]{String.valueOf(numUnsentForms)})); String syncStatus = ""; if (notificationText != null) { syncStatus = notificationText; } else if (numUnsentForms == 0) { syncStatus = lastSyncTimeAndMessage.second; } if (numUnsentForms != 0 || HiddenPreferences.shouldShowUnsentFormsWhenZero()) { if (!TextUtils.isEmpty(syncStatus)) { syncStatus += "\n\n"; } syncStatus += syncIndicator; } squareButtonViewHolder.subTextView.setText(syncStatus); setSyncSubtextColor( squareButtonViewHolder.subTextView, numUnsentForms, lastSyncTimeAndMessage.first, activity.getResources().getColor(cardDisplayData.subTextColor), activity.getResources().getColor(R.color.cc_dark_warm_accent_color)); }
Example #29
Source File: BaseMovementMethod.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Performs a scroll to line start action. * Scrolls to the start of the line. * * @param widget The text view. * @param buffer The text buffer. * @return True if the event was handled. * @hide */ protected boolean scrollLineStart(TextView widget, Spannable buffer) { final int minScrollX = getScrollBoundsLeft(widget); int scrollX = widget.getScrollX(); if (scrollX > minScrollX) { widget.scrollTo(minScrollX, widget.getScrollY()); return true; } return false; }
Example #30
Source File: GalgoService.java From galgo with Apache License 2.0 | 5 votes |
private void redraw(Collection<String> texts) { mTextView.setTextSize(mOptions.textSize); mTextView.setTextColor(mOptions.textColor); Spannable spannable = new SpannableString(TextUtils.join("\n", texts)); spannable.setSpan(new BackgroundColorSpan(mOptions.backgroundColor), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mTextView.setText(spannable); }