android.text.SpannableStringBuilder Java Examples
The following examples show how to use
android.text.SpannableStringBuilder.
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: ImageSpanTarget.java From android-proguards with Apache License 2.0 | 6 votes |
@Override public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) { TextView tv = textView.get(); if (tv != null) { BitmapDrawable bitmapDrawable = new BitmapDrawable(tv.getResources(), bitmap); // image span doesn't handle scaling so we manually set bounds if (bitmap.getWidth() > tv.getWidth()) { float aspectRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth(); bitmapDrawable.setBounds(0, 0, tv.getWidth(), (int) (aspectRatio * tv.getWidth())); } else { bitmapDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); } ImageSpan span = new ImageSpan(bitmapDrawable); // add the image span and remove our marker SpannableStringBuilder ssb = new SpannableStringBuilder(tv.getText()); int start = ssb.getSpanStart(loadingSpan); int end = ssb.getSpanEnd(loadingSpan); if (start >= 0 && end >= 0) { ssb.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } ssb.removeSpan(loadingSpan); // animate the change TransitionManager.beginDelayedTransition((ViewGroup) tv.getParent()); tv.setText(ssb); } }
Example #2
Source File: ConfirmInfoBar.java From android-chromium with BSD 2-Clause "Simplified" License | 6 votes |
@Override public CharSequence getMessageText(Context context) { // Construct text to be displayed on the infobar. SpannableStringBuilder infobarMessage = new SpannableStringBuilder(mMessage); // If we have a link text to display, append it. if (!TextUtils.isEmpty(mLinkText)) { SpannableStringBuilder spannableLinkText = new SpannableStringBuilder(mLinkText); ClickableSpan onLinkClicked = new ClickableSpan() { @Override public void onClick(View view) { onLinkClicked(); } }; spannableLinkText.setSpan(onLinkClicked, 0, spannableLinkText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); infobarMessage.append(" "); infobarMessage.append(spannableLinkText); } return infobarMessage; }
Example #3
Source File: ImageClassifierTF.java From AIIA-DNN-benchmark with Apache License 2.0 | 6 votes |
/** Classifies a frame from the preview stream. */ void classifyFrame(Bitmap bitmap, SpannableStringBuilder builder) { if (tflite == null) { Log.e(TAG, "Image classifier has not been initialized; Skipped."); builder.append(new SpannableString("Uninitialized Classifier.")); } convertBitmapToByteBuffer(bitmap); // Here's where the magic happens!!! long startTime = SystemClock.uptimeMillis(); runInference(); long endTime = SystemClock.uptimeMillis(); Log.d(TAG, "Timecost to run model inference: " + Long.toString(endTime - startTime)); // Smooth the results across frames. applyFilter(); // Print the results. printTopKLabels(builder); long duration = endTime - startTime; SpannableString span = new SpannableString(duration + " ms"); span.setSpan(new ForegroundColorSpan(android.graphics.Color.LTGRAY), 0, span.length(), 0); builder.append(span); }
Example #4
Source File: SpannableBuilderTest.java From Markwon with Apache License 2.0 | 6 votes |
@Test public void spans_reversed() { // resulting SpannableStringBuilder should have spans reversed final Object[] spans = { 0, 1, 2 }; for (Object span : spans) { builder.append(span.toString(), span); } final SpannableStringBuilder spannableStringBuilder = builder.spannableStringBuilder(); final Object[] actual = spannableStringBuilder.getSpans(0, builder.length(), Object.class); for (int start = 0, length = spans.length, end = length - 1; start < length; start++, end--) { assertEquals(spans[start], actual[end]); } }
Example #5
Source File: AnswerTextBuilder.java From 365browser with Apache License 2.0 | 6 votes |
/** * Builds a Spannable containing all of the styled text in the supplied ImageLine. * * @param line All text fields within this line will be added to the returned Spannable. * types. * @param metrics Font metrics which will be used to properly size and layout images and top- * aligned text. * @param density Screen density which will be used to properly size and layout images and top- * aligned text. */ static Spannable buildSpannable( SuggestionAnswer.ImageLine line, Paint.FontMetrics metrics, float density) { SpannableStringBuilder builder = new SpannableStringBuilder(); // Determine the height of the largest text element in the line. This // will be used to top-align text and scale images. int maxTextHeightSp = getMaxTextHeightSp(line); List<SuggestionAnswer.TextField> textFields = line.getTextFields(); for (int i = 0; i < textFields.size(); i++) { appendAndStyleText(builder, textFields.get(i), maxTextHeightSp, metrics, density); } if (line.hasAdditionalText()) { builder.append(" "); SuggestionAnswer.TextField additionalText = line.getAdditionalText(); appendAndStyleText(builder, additionalText, maxTextHeightSp, metrics, density); } if (line.hasStatusText()) { builder.append(" "); SuggestionAnswer.TextField statusText = line.getStatusText(); appendAndStyleText(builder, statusText, maxTextHeightSp, metrics, density); } return builder; }
Example #6
Source File: PermissionDialogController.java From 365browser with Apache License 2.0 | 6 votes |
private CharSequence prepareMainMessageString(final PermissionDialogDelegate delegate) { SpannableStringBuilder fullString = new SpannableStringBuilder(); String messageText = delegate.getMessageText(); String linkText = delegate.getLinkText(); if (!TextUtils.isEmpty(messageText)) fullString.append(messageText); // If the linkText exists, then wrap it in a clickable span and concatenate it with the main // dialog message. if (!TextUtils.isEmpty(linkText)) { if (fullString.length() > 0) fullString.append(" "); int spanStart = fullString.length(); fullString.append(linkText); fullString.setSpan(new ClickableSpan() { @Override public void onClick(View view) { mDecision = NOT_DECIDED; delegate.onLinkClicked(); if (mDialog != null) mDialog.dismiss(); } }, spanStart, fullString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return fullString; }
Example #7
Source File: MarkwonEditorImplTest.java From Markwon with Apache License 2.0 | 6 votes |
@Test public void process() { // create markwon final Markwon markwon = Markwon.create(RuntimeEnvironment.application); // default punctuation final MarkwonEditor editor = MarkwonEditor.create(markwon); final SpannableStringBuilder builder = new SpannableStringBuilder("**bold**"); editor.process(builder); final PunctuationSpan[] spans = builder.getSpans(0, builder.length(), PunctuationSpan.class); assertEquals(2, spans.length); final PunctuationSpan first = spans[0]; assertEquals(0, builder.getSpanStart(first)); assertEquals(2, builder.getSpanEnd(first)); final PunctuationSpan second = spans[1]; assertEquals(6, builder.getSpanStart(second)); assertEquals(8, builder.getSpanEnd(second)); }
Example #8
Source File: RichEditText.java From GSYRickText with MIT License | 6 votes |
/** * 添加了@的加入 * * @param userModel 用户实体 */ public void resolveText(UserModel userModel) { String userName = userModel.getUser_name(); userModel.setUser_name(userName + "\b"); nameList.add(userModel); int index = getSelectionStart(); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(getText()); //直接用span会导致后面没文字的时候新输入的一起变色 Spanned htmlText = Html.fromHtml(String.format("<font color='%s'>" + userName + "</font>", colorAtUser)); spannableStringBuilder.insert(index, htmlText); spannableStringBuilder.insert(index + htmlText.length(), "\b"); setText(spannableStringBuilder); setSelection(index + htmlText.length() + 1); }
Example #9
Source File: HtmlParser.java From Overchan-Android with GNU General Public License v3.0 | 6 votes |
public HtmlToSpannedConverter(String subject, String source, ThemeColors colors, HtmlParser.ImageGetter imageGetter, boolean openSpoilers, Parser parser) { mSource = source; mSpannableStringBuilder = new SpannableStringBuilder(); if (!TextUtils.isEmpty(subject)) { mSpannableStringBuilder.append(subject); int len = mSpannableStringBuilder.length(); mSpannableStringBuilder.setSpan(new RelativeSizeSpan(1.25f), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mSpannableStringBuilder.setSpan(new StyleSpan(Typeface.BOLD), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (colors != null) { mSpannableStringBuilder.setSpan(new ForegroundColorSpan(colors.subjectForeground), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } mSpannableStringBuilder.append('\n'); mStartLength = mSpannableStringBuilder.length(); } mColors = colors; mOpenSpoilers = openSpoilers; mImageGetter = imageGetter; mReader = parser; }
Example #10
Source File: HtmlParser.java From Overchan-Android with GNU General Public License v3.0 | 6 votes |
private static void endBlockquote(SpannableStringBuilder text, ThemeColors colors) { int len = text.length(); Object obj = getLast(text, Blockquote.class); int where = text.getSpanStart(obj); text.removeSpan(obj); if (where != len) { Blockquote b = (Blockquote) obj; if (b.mIsUnkfunc) { if (colors != null) { text.setSpan(new ForegroundColorSpan(colors.quoteForeground), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } else { text.setSpan(new QuoteSpan(), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } }
Example #11
Source File: MessageFormatter.java From talk-android with MIT License | 6 votes |
public static Spannable formatHighlightSpan(String html, Resources res) { HighlightSpan highlightSpan; if (Html.fromHtml(html) instanceof SpannableStringBuilder) { SpannableStringBuilder value = (SpannableStringBuilder) Html.fromHtml(html); StyleSpan[] spans = value.getSpans(0, html.length(), StyleSpan.class); for (StyleSpan span : spans) { int start = value.getSpanStart(span); int end = value.getSpanEnd(span); value.removeSpan(span); highlightSpan = new HighlightSpan(res); value.setSpan(highlightSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return value; } else { return new SpannableStringBuilder(html); } }
Example #12
Source File: CreditCardDescriptorModel.java From px-android with MIT License | 6 votes |
@Override protected String getAccessibilityContentDescription(@NonNull final Context context) { final SpannableStringBuilder builder = new SpannableStringBuilder(); final PayerCost currentInstallment = getCurrent(); final String money = context.getResources().getString(R.string.px_money); builder .append(currentInstallment.getInstallments().toString()) .append(TextUtil.SPACE) .append(context.getResources().getString(R.string.px_date_divider)) .append(TextUtil.SPACE) .append(currentInstallment.getInstallmentAmount().toString()) .append(TextUtil.SPACE) .append(money) .append(TextUtil.SPACE) .append(hasAmountDescriptor() ? currentInstallment.getTotalAmount().floatValue() + money : TextUtil.EMPTY) .append(hasInterestFree() ? interestFree.getInstallmentRow().getMessage() : TextUtil.EMPTY); updateCFTSpannable(builder, context); updateInstallmentsInfo(builder, context); return builder.toString(); }
Example #13
Source File: HtmlParser.java From Overchan-Android with GNU General Public License v3.0 | 6 votes |
private static void handleP(SpannableStringBuilder text, int startLength, int[] lastPTagLengthRefs) { lastPTagLengthRefs[0] = text.length(); int len = text.length() - startLength; if (len >= 1 && text.charAt(text.length() - 1) == '\n') { if (len >= 2 && text.charAt(text.length() - 2) == '\n') { lastPTagLengthRefs[1] = text.length(); return; } text.append("\n"); lastPTagLengthRefs[1] = text.length(); return; } if (len != 0) { text.append("\n\n"); } lastPTagLengthRefs[1] = text.length(); }
Example #14
Source File: EmojiView.java From TelePlus-Android with GNU General Public License v2.0 | 6 votes |
private void sendEmoji(String override) { String code = override != null ? override : (String) getTag(); SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(code); if (override == null) { if (pager.getCurrentItem() != 0) { String color = Emoji.emojiColor.get(code); if (color != null) { code = addColorToCode(code, color); } } addEmojiToRecent(code); if (listener != null) { listener.onEmojiSelected(Emoji.fixEmoji(code)); } } else { if (listener != null) { listener.onEmojiSelected(Emoji.fixEmoji(override)); } } }
Example #15
Source File: PreHookSqlTest.java From cwac-saferoom with Apache License 2.0 | 5 votes |
@Test public void testPreKeySql() throws IOException { SafeHelperFactory.Options options = SafeHelperFactory.Options.builder().setPreKeySql(PREKEY_SQL).build(); SafeHelperFactory factory= SafeHelperFactory.fromUser(new SpannableStringBuilder(PASSPHRASE), options); SupportSQLiteOpenHelper helper= factory.create(InstrumentationRegistry.getTargetContext(), DB_NAME, new Callback(1)); SupportSQLiteDatabase db=helper.getWritableDatabase(); assertEquals(1, db.getVersion()); db.close(); }
Example #16
Source File: SubmissionCache.java From Slide with GNU General Public License v3.0 | 5 votes |
public static SpannableStringBuilder getCrosspostLine(Submission s, Context mContext) { if (crosspost == null) crosspost = new WeakHashMap<>(); if (crosspost.containsKey(s.getFullName())) { return crosspost.get(s.getFullName()); } else { return getCrosspostSpannable(s, mContext); } }
Example #17
Source File: MongolTextStorage.java From mongol-library with MIT License | 5 votes |
private void updateGlyphTextForUnicodeRange(int start, int end) { if (!(mUnicodeText instanceof Spanned)) return; // add spans to glyph string CharacterStyle[] spans = ((Spanned) mUnicodeText).getSpans(start, end, CharacterStyle.class); for (CharacterStyle span : spans) { final int unicodeStart = ((Spanned) mUnicodeText).getSpanStart(span); final int unicodeEnd = ((Spanned) mUnicodeText).getSpanEnd(span); ((SpannableStringBuilder) mGlyphText).setSpan(span, unicodeStart, unicodeEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } }
Example #18
Source File: SearchHighlight.java From actor-platform with GNU Affero General Public License v3.0 | 5 votes |
public static Spannable highlightMentionsQuery(String src, List<StringMatch> matches, int color) { SpannableStringBuilder builder = new SpannableStringBuilder(src); for (StringMatch sm : matches) { builder.setSpan(new ForegroundColorSpan(color), sm.getStart(), sm.getStart() + sm.getLength(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } return builder; }
Example #19
Source File: ConverterHtmlToSpanned.java From memoir with Apache License 2.0 | 5 votes |
private void removeTrailingLineBreaks() { int end = mResult.length(); while (end > 0 && mResult.charAt(end - 1) == '\n') { end--; } if (end < mResult.length()) { mResult = SpannableStringBuilder.valueOf(mResult.subSequence(0, end)); } }
Example #20
Source File: MainActivity.java From drawee-text-view with Apache License 2.0 | 5 votes |
private CharSequence[] buildArray() { CharSequence[] sequences = new CharSequence[EMOTIONS.length * 2]; for (int i = 0; i < sequences.length; i++) { SpannableStringBuilder builder = new SpannableStringBuilder(); String emotion = EMOTIONS[i % EMOTIONS.length]; builder.append(emotion).append('\n'); int start = builder.length(); builder.append("[emotion]"); builder.setSpan(new DraweeSpan.Builder(emotion).setLayout(140, 140).build(), start, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); builder.append("~~~~~~~~~~~~~~~~~~"); sequences[i] = builder; } return sequences; }
Example #21
Source File: RichEditor.java From RichEditor with MIT License | 5 votes |
public <T extends Styleable> int startStyleWithRange(Style<T> style, int start, int end, Object... args) { SpannableStringBuilder spannableStringBuilder = getSSB(); int flag = start == end ? Spanned.SPAN_INCLUSIVE_INCLUSIVE : Spanned.SPAN_EXCLUSIVE_INCLUSIVE; Styleable span = style.needArgument() ? style.createSpan(args) : style.createSpan(); if (style instanceof StyleExt) { ((StyleExt) style).beforeStyle(spannableStringBuilder, start, end); } startStyle(start, end, spannedProvider.getSSB(), span, flag); if (style instanceof StyleExt) { ((StyleExt) style).afterStyle(spannableStringBuilder, start, end); } return StyleTypeStateSpec.StyleTypeState.STATE_ACTIVE; }
Example #22
Source File: AudioBookAdapter.java From HaoReader with GNU General Public License v3.0 | 5 votes |
private SpannableStringBuilder getBookName(String name, int newChapters) { SpannableStringBuilder sbs = new SpannableStringBuilder(name); if (newChapters == 0) { return sbs; } SpannableString chaptersSpan = new SpannableString(String.format(Locale.getDefault(), "(新增%d章)", newChapters)); chaptersSpan.setSpan(new RelativeSizeSpan(0.75f), 0, chaptersSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); chaptersSpan.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.colorTextSecondary)), 0, chaptersSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); sbs.append(chaptersSpan); return sbs; }
Example #23
Source File: EditorFragment.java From android-discourse with Apache License 2.0 | 5 votes |
private void pushToStack(int id) { Editable editable = mContentET.getText(); mHistories.push(new SpannableStringBuilder(editable)); L.d(mContentET.getText().toString()); mHistoriesSelection.push(getContentSelection()); mHistoriyActions.push(mLastAction); }
Example #24
Source File: CustomHtmlToSpannedConverter.java From zulip-android with Apache License 2.0 | 5 votes |
private static void startStreamA(SpannableStringBuilder text, Attributes attributes) { /** example: <a class="stream" data-stream-id="4" href="/#narrow/stream/android">#android</a> */ String streamId = attributes.getValue("data-stream-id"); int len = text.length(); text.setSpan(new Href(streamId), len, len, Spannable.SPAN_MARK_MARK); }
Example #25
Source File: DefaultDecorator.java From kaif-android with Apache License 2.0 | 5 votes |
private void appendParagraphNewLines(SpannableStringBuilder out) { int len = out.length(); if (len >= 1 && out.charAt(len - 1) == '\n') { if (len >= 2 && out.charAt(len - 2) == '\n') { return; } out.append("\n"); return; } if (out.length() != 0) { out.append("\n\n"); } }
Example #26
Source File: MedalRemindProcessor.java From imsdk-android with MIT License | 5 votes |
@Override public void processChatView(ViewGroup parent, final IMessageItem item) { IMMessage message = item.getMessage(); final Context context = item.getContext(); try { MedalRemindDataBean meetingDataBean = JsonUtils.getGson().fromJson(message.getExt() , MedalRemindDataBean.class); MedalClickRemindView meetingRemindView = ViewPool.getView(MedalClickRemindView.class, context); SpannableStringBuilder sb = new SpannableStringBuilder(); String[] strs = meetingDataBean.getStrMap().getAllStr().split(meetingDataBean.getStrMap().getHighlightStr()); Spanned color = Html.fromHtml("<font color='#00cabe'>" + meetingDataBean.getStrMap().getHighlightStr() + "</font>"); if (strs.length > 1) { sb.append(strs[0]); sb.append(color); sb.append(strs[1]); } meetingRemindView.setSB(sb); meetingRemindView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // context.startActivity( FlutterMedalActivity.makeIntent(context,CurrentPreference.getInstance().getPreferenceUserId())); } }); parent.setVisibility(View.VISIBLE); parent.addView(meetingRemindView); } catch (Exception e) { e.printStackTrace(); } }
Example #27
Source File: Message.java From Conversations with GNU General Public License v3.0 | 5 votes |
public SpannableStringBuilder getMergedBody() { SpannableStringBuilder body = new SpannableStringBuilder(MessageUtils.filterLtrRtl(this.body).trim()); Message current = this; while (current.mergeable(current.next())) { current = current.next(); if (current == null) { break; } body.append("\n\n"); body.setSpan(new MergeSeparator(), body.length() - 2, body.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); body.append(MessageUtils.filterLtrRtl(current.getBody()).trim()); } return body; }
Example #28
Source File: StickerSetNameCell.java From Telegram-FOSS with GNU General Public License v2.0 | 5 votes |
private void updateUrlSearchSpan() { if (url != null) { SpannableStringBuilder builder = new SpannableStringBuilder(url); try { builder.setSpan(new ColorSpanUnderline(Theme.getColor(Theme.key_chat_emojiPanelStickerSetNameHighlight)), 0, urlSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan(new ColorSpanUnderline(Theme.getColor(Theme.key_chat_emojiPanelStickerSetName)), urlSearchLength, url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception ignore) { } urlTextView.setText(builder); } }
Example #29
Source File: OutlineItemView.java From mOrgAnd with GNU General Public License v2.0 | 5 votes |
private void setupUrls(SpannableStringBuilder stringBuilder) { Matcher matcher = OrgNodeUtils.urlPattern.matcher(stringBuilder); int currentIndex = 0; while(matcher.find(currentIndex)) { int beginIndex = matcher.start(); final String url = matcher.group(1) != null ? matcher.group(1) : matcher.group(3); String alias = matcher.group(2) != null ? matcher.group(2) : url; stringBuilder.delete(matcher.start(), matcher.end()); currentIndex = beginIndex + alias.length(); stringBuilder.insert(beginIndex, alias); ClickableSpan clickable = new ClickableSpan() { public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { Application.getInstace().getApplicationContext().startActivity(intent); } catch (ActivityNotFoundException ex) { ex.printStackTrace(); } } }; stringBuilder.setSpan(clickable, beginIndex, currentIndex, 0); matcher = OrgNodeUtils.urlPattern.matcher(stringBuilder); } }
Example #30
Source File: FeedEditText.java From umeng_community_android with MIT License | 5 votes |
/** * 封装赞的TextView * * @param str * @return */ public void atFriends(List<CommUser> friends) { if (friends == null) { return; } // removeNonexistFriend(friends); // 光标的位置 int editSection = getCursorPos(); Log.d("", "### atFriends, start = " + editSection); SpannableStringBuilder ssb = new SpannableStringBuilder(getText()); int count = friends.size(); for (int i = 0; i < count; i++) { final CommUser user = friends.get(i); // 如果已经有了该好友,则直接返回 if (mAtMap.containsValue(user)) { continue; } isDecorating = true; final String name = "@" + user.name + " "; ssb.insert(editSection, name); setText(ssb); // 更新map索引 updateMapIndex(editSection, name.length()); // 将所有at的位置存储在map中 mAtMap.put(editSection, user); // 更新起始点 editSection += name.length(); } // 包装文本 decorateText(); isDecorating = false; // 此时将光标移动到文本末尾 setSelection(getText().length()); mCursorIndex = editSection; }