private void initMarqueeView3() { SimpleMF<Spanned> marqueeFactory3 = new SimpleMF<>(MainActivity.this); List<Spanned> datas3 = new ArrayList<>(); datas3.add(Html.fromHtml("<font color=\"#ff0000\">《赋得古原草送别》</font>")); datas3.add(Html.fromHtml("<font color=\"#00ff00\">离离原上草,</font>一岁一枯荣。")); datas3.add(Html.fromHtml("野火烧不尽,<font color=\"#0000ff\">春风吹又生。</font>")); datas3.add(Html.fromHtml("<font color=\"#333333\">远芳侵古道,晴翠接荒城。</font>")); datas3.add(Html.fromHtml("<font color=\"#ffffff\">又送王孙去,萋萋满别情。</font>")); marqueeFactory3.setData(datas3); marqueeView3.setMarqueeFactory(marqueeFactory3); marqueeView3.startFlipping(); marqueeFactory3.setOnItemClickListener(new MarqueeFactory.OnItemClickListener<TextView, Spanned>() { @Override public void onItemClickListener(MarqueeFactory.ViewHolder<TextView, Spanned> holder) { Toast.makeText(MainActivity.this, holder.data, Toast.LENGTH_SHORT).show(); } }); }
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) { int st = ((Spanned) text).getSpanStart(this); int itop = layout.getLineTop(layout.getLineForOffset(st)); if (dir < 0) x -= mBitmap.getWidth(); int delta = totalHeight - mBitmap.getHeight(); if (delta > 0) { if (mVerticalAlignment == ALIGN_TOP) { c.drawBitmap(mBitmap, x, itop, p); } else if (mVerticalAlignment == ALIGN_CENTER) { c.drawBitmap(mBitmap, x, itop + delta / 2, p); } else { c.drawBitmap(mBitmap, x, itop + delta, p); } } else { c.drawBitmap(mBitmap, x, itop, p); } }
/** * Prepares text to be displayed as the infobar's main message, including setting up a * clickable link if the infobar requires it. */ private CharSequence prepareMainMessageString() { SpannableStringBuilder fullString = new SpannableStringBuilder(); if (mMessageMainText != null) fullString.append(mMessageMainText); // Concatenate the text to display for the link and make it clickable. if (!TextUtils.isEmpty(mMessageLinkText)) { if (fullString.length() > 0) fullString.append(" "); int spanStart = fullString.length(); fullString.append(mMessageLinkText); fullString.setSpan(new ClickableSpan() { @Override public void onClick(View view) { mInfoBarView.onLinkClicked(); } }, spanStart, fullString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return fullString; }
@Test public void testTextDecorationLineLineThroughApplied() { UIManagerModule uiManager = getUIManagerModule(); ReactRootView rootView = createText( uiManager, JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "line-through"), JavaOnlyMap.of(ReactTextShadowNode.PROP_TEXT, "test text")); TextView textView = (TextView) rootView.getChildAt(0); Spanned text = (Spanned) textView.getText(); UnderlineSpan[] underlineSpans = text.getSpans(0, text.length(), UnderlineSpan.class); StrikethroughSpan strikeThroughSpan = getSingleSpan(textView, StrikethroughSpan.class); assertThat(underlineSpans).hasSize(0); assertThat(strikeThroughSpan instanceof StrikethroughSpan).isTrue(); }
protected void createMastodonApi() { mastodonApiDispatcher = new Dispatcher(); Gson gson = new GsonBuilder() .registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()) .create(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); OkHttpClient.Builder okBuilder = OkHttpUtils.getCompatibleClientBuilder(preferences) .addInterceptor(new AuthInterceptor(this)) .dispatcher(mastodonApiDispatcher); if (BuildConfig.DEBUG) { okBuilder.addInterceptor( new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)); } Retrofit retrofit = new Retrofit.Builder().baseUrl(getBaseUrl()) .client(okBuilder.build()) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); mastodonApi = retrofit.create(MastodonApi.class); }
public void setText(String text) { int startIndex = 0; while (true) { int start = text.indexOf("《"); int end = text.indexOf("》"); if (start < 0 || end < 0) { append(text.substring(startIndex)); break; } append(text.substring(startIndex, start)); SpannableString spanableInfo = new SpannableString(text.substring(start, end + 1)); spanableInfo.setSpan(new Clickable(spanableInfo.toString()), 0, end + 1 - start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); append(spanableInfo); //setMovementMethod()该方法必须调用,否则点击事件不响应 setMovementMethod(LinkMovementMethod.getInstance()); text = text.substring(end + 1); LogUtils.e(spanableInfo.toString()); } }
private void readNode(Object node, Table table) { if (node instanceof TagNode) { TagNode tagNode = (TagNode) node; if (tagNode.getName().equals("td") || tagNode.getName().equals("th")) { Spanned result = this.getSpanner().fromTagNode(tagNode); table.addCell(result); return; } if (tagNode.getName().equals("tr")) { table.addRow(); } for (Object child : tagNode.getChildTags()) { readNode(child, table); } } }
private static final void applyLink(String url, int start, int end, Spannable text, final ColorStateList linkColor, final ColorStateList bgColor, QMUIOnSpanClickListener l) { text.setSpan(new StyleableURLSpan(url, l) { @Override public void updateDrawState(TextPaint ds) { if (linkColor != null) { int normalLinkColor = linkColor.getColorForState(new int[]{android.R.attr.state_enabled, -android.R.attr.state_pressed}, Color.TRANSPARENT); int pressedLinkColor = linkColor.getColorForState(new int[]{android.R.attr.state_pressed}, normalLinkColor); ds.linkColor = mPressed ? pressedLinkColor : normalLinkColor; } if (bgColor != null) { int normalBgColor = bgColor.getColorForState(new int[]{android.R.attr.state_enabled, -android.R.attr.state_pressed}, Color.TRANSPARENT); int pressedBgColor = bgColor.getColorForState(new int[]{android.R.attr.state_pressed}, normalBgColor); ds.bgColor = mPressed ? pressedBgColor : normalBgColor; } super.updateDrawState(ds); ds.setUnderlineText(false); } }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); }
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 RichEditText.TagSpan(str), matcherStart, matcherEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); log("matchMention:" + str + " " + matcherStart + " " + matcherEnd); } return spannable; }
@Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (end - start == 1) { char c = source.charAt(0); if (c == '.' || c == ',') { onDotOrComma(); return ""; } if (isIncomeExpenseEnabled()) { if (c == '-') { setExpense(); return ""; } if (c == '+') { setIncome(); return ""; } } } return super.filter(source, start, end, dest, dstart, dend); }
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(); }
@SuppressWarnings("Range") // Lint bug: the if makes sure waveCharDelay >= 0 private JumpingBeansSpan[] buildWavingSpans(SpannableStringBuilder sbb) { JumpingBeansSpan[] spans; if (waveCharDelay == DEFAULT_WAVE_CHAR_DELAY) { waveCharDelay = loopDuration / (3 * (endPos - startPos)); } spans = new JumpingBeansSpan[endPos - startPos]; for (int pos = startPos; pos < endPos; pos++) { JumpingBeansSpan jumpingBean = new JumpingBeansSpan(textView, loopDuration, pos - startPos, waveCharDelay, animRange); sbb.setSpan(jumpingBean, pos, pos + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spans[pos - startPos] = jumpingBean; } return spans; }
@Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { // check black-list set for (int i = 0; i < source.length(); i++) { // LogUtil.e(Integer.toHexString(source.charAt(i))); } // LogUtil.e(source.toString() + " length: " + source.toString().length() + // " ;bytes length: " + source.toString().getBytes().length); // Iterator<String> iterator = filterSet.iterator(); // while (iterator.hasNext()) { // String filter = iterator.next(); // if (filter.equals(source.toString())) { // LogUtil.e(filter + " length: " + filter.length() + // " ;bytes length: " + filter.getBytes().length); // for (int i= 0; i < source.length(); i++){ // LogUtil.e(Integer.toHexString(source.charAt(i))); // } // return ""; // } // } if (filterSet.contains(source.toString())) { return ""; } return source; }
private Spanned formatText(String input) { BaseModule bm = mDisplay.mLogic.mBaseModule; if(CalculatorSettings.digitGrouping(getContext())) { // Add grouping, and then split on the selection handle // which is saved as a unique char String grouped = bm.groupSentence(input, selectionHandle); if(grouped.contains(String.valueOf(BaseModule.SELECTION_HANDLE))) { String[] temp = grouped.split(String.valueOf(BaseModule.SELECTION_HANDLE)); selectionHandle = temp[0].length(); input = ""; for(String s : temp) { input += s; } } else { input = grouped; selectionHandle = input.length(); } } return Html.fromHtml(mEquationFormatter.insertSupscripts(input)); }
@Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0x001: SpannableString string = new SpannableString("设置文字的前景色为淡蓝色"); RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.5f); string.setSpan(sizeSpan, pos, pos + 1, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); bgtext.setText(string); pos++; if (pos >= bgtext.getText().length()) { pos = 0; } Message ms = Message.obtain(); ms.what = 0x001; handler.sendEmptyMessageDelayed(0x001, 150); break; } }
@NonNull public CharSequence removeFromEnd(int start) { // this method is not intended to be used by clients // it's a workaround to support tables final int end = length(); // as we do not expose builder and do no apply spans to it, we are safe to NOT to convert to String final SpannableStringBuilderImpl impl = new SpannableStringBuilderImpl(builder.subSequence(start, end)); final Iterator<Span> iterator = spans.iterator(); Span span; while (iterator.hasNext() && ((span = iterator.next())) != null) { if (span.start >= start && span.end <= end) { impl.setSpan(span.what, span.start - start, span.end - start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); iterator.remove(); } } builder.replace(start, end, ""); return impl; }
/** * Input frame character length limit * * @param mEdit EditText * @param maxLength maxLength */ public void setEditable(EditText mEdit, int maxLength) { if (mEdit.getText().length() < maxLength) { mEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength) { }}); mEdit.setCursorVisible(true); mEdit.setFocusableInTouchMode(true); mEdit.requestFocus(); } else { mEdit.setFilters(new InputFilter[]{new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { return source.length() < 1 ? dest.subSequence(dstart, dend) : ""; } }}); mEdit.setCursorVisible(false); mEdit.setFocusableInTouchMode(false); mEdit.clearFocus(); } }
public static Spanned getSpannedString(String str, String sub) { String lowerCase = str.toLowerCase(); String stag = "<font color='#2196F3'>", etag = "</font>"; int atIndx = 0; int ind = -1; int curInc = 0; while ((ind = lowerCase.indexOf(sub, atIndx)) != -1) { Log.d("Utils", "getSpannableString: =" + ind); str = str.substring(0, ind + curInc) + stag + str.substring(ind + curInc, ind + curInc + sub.length()) + etag + str.substring(ind + curInc + sub.length(), str.length()); atIndx = ind + sub.length(); curInc += stag.length() + etag.length(); } return Html.fromHtml(str); }
@Override protected void internalUpdate(XySeriesInfo seriesInfo) { final SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(modifierName).append(StringUtil.NEW_LINE); if (seriesInfo.seriesName != null) { sb.append(seriesInfo.seriesName); sb.setSpan(new ForegroundColorSpan(ColorUtil.Black), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); sb.append(StringUtil.NEW_LINE); } sb.append("X: ").append(seriesInfo.getFormattedXValue()); sb.append(" Y: ").append(seriesInfo.getFormattedYValue()); setText(sb); // stroke 0xffff4500 setSeriesColor(0xffe2460c); }
/** * Create a spanned string that contains RoundedCornersBackgroundSpan. * * @return spanned string */ public Spannable build() { if (mTextParts.isEmpty()) { throw new IllegalArgumentException("You must specify at least one text part."); } boolean first = true; final SpannableStringBuilder builder = new SpannableStringBuilder(); mSeparatorWidth = 2 * mPadding + mPartsSpacing; for (final Pair<CharSequence, BackgroundHolder> stringPart : mTextParts) { if (first) { first = false; } else { final int start = builder.length(); builder.append(" "); final SpacingSpan spacingSpan = SpacingSpan.newInstance(mSeparatorWidth); builder.setSpan(spacingSpan, start, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } stringPart.second.setStart(builder.length()); builder.append(stringPart.first); stringPart.second.setEnd(builder.length()); } final RoundedCornersBackgroundSpan span = new RoundedCornersBackgroundSpan(this); builder.setSpan(span, 0, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return builder; }
/** * Returns <code>text</code>, modified, if necessary, to ensure that * it ends with a token terminator (for example a space or comma). * It is a method from the MultiAutoCompleteTextView.Tokenizer interface. */ public CharSequence terminateToken(CharSequence text) { int i = text.length(); while (i > 0 && text.charAt(i - 1) == ' ') { i--; } char c; if (i > 0 && ((c = text.charAt(i - 1)) == ',' || c == ';')) { return text; } else { // Use the same delimiter the user just typed. // This lets them have a mixture of commas and semicolons in their list. String separator = mLastSeparator + " "; if (text instanceof Spanned) { SpannableString sp = new SpannableString(text + separator); TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0); return sp; } else { return text + separator; } } }
/** * 中横线,即删除线 * * @param isMidLine isMidLine */ void setMidLine(boolean isMidLine, int index) { if (index >= 0 && index < mSections.size()) { mSections.get(index).setMidLine(isMidLine); } Editable edit = getEditableText(); int star = getSectionStart(); int end = getSectionEnd(); if (isMidLine) { edit.setSpan(new StrikethroughSpan(), star, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { StrikethroughSpan[] styleSpans = edit.getSpans(star, end, StrikethroughSpan.class); for (StrikethroughSpan span : styleSpans) { edit.removeSpan(span); } } }
/** * Will not auto dismiss */ public void createDialogMessage(String header, Spanned body, String pos, String neg, String neu, MaterialDialog.SingleButtonCallback buttonCallback) { // Build the alert dialog new MaterialDialog.Builder(mContext) .onAny(buttonCallback) .positiveText(pos) .negativeText(neg) .neutralText(neu) .autoDismiss(false) .typeface(Typeface.SANS_SERIF,Typeface.SANS_SERIF) .iconRes(app_prefs.isLightTheme()?R.drawable.ic_new_releases_black_24dp:R.drawable.ic_new_releases_white_24dp) .buttonRippleColorRes(R.color.colorAccent) .positiveColorRes(R.color.colorStateBlue) .negativeColorRes(R.color.colorStateOrange) .theme(app_prefs.isLightTheme()?Theme.LIGHT:Theme.DARK) .title(header) .content(body) .show(); }
public static SpannableStringBuilder getTeaser(Context ctx, Spanned body) { if (body.length() < TEASER_LENGTH) throw new IllegalArgumentException( "String is shorter than TEASER_LENGTH"); SpannableStringBuilder builder = new SpannableStringBuilder(body.subSequence(0, TEASER_LENGTH)); String ellipsis = ctx.getString(R.string.ellipsis); builder.append(ellipsis).append(" "); Spannable readMore = new SpannableString( ctx.getString(R.string.read_more) + ellipsis); ForegroundColorSpan fg = new ForegroundColorSpan( ContextCompat.getColor(ctx, R.color.briar_text_link)); readMore.setSpan(fg, 0, readMore.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.append(readMore); return builder; }
@SuppressLint("SetTextI18n") @Override public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) { HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder; setTypeIcon(headerViewHolder); headerViewHolder.mTypeTv.setText(title); // headerViewHolder.mTypeRankBtn.setOnClickListener(v -> mContext.startActivity( // new Intent(mContext, OriginalRankActivity.class))); switch (type) { case TYPE_RECOMMENDED: headerViewHolder.mTypeMore.setVisibility(View.GONE); headerViewHolder.mTypeRankBtn.setVisibility(View.VISIBLE); headerViewHolder.mAllLiveNum.setVisibility(View.GONE); break; case TYPE_LIVE: headerViewHolder.mTypeRankBtn.setVisibility(View.GONE); headerViewHolder.mTypeMore.setVisibility(View.VISIBLE); headerViewHolder.mAllLiveNum.setVisibility(View.VISIBLE); SpannableStringBuilder stringBuilder = new SpannableStringBuilder("当前" + liveCount + "个直播"); ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan( mContext.getResources().getColor(R.color.pink)); stringBuilder.setSpan(foregroundColorSpan, 2, stringBuilder.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); headerViewHolder.mAllLiveNum.setText(stringBuilder); break; default: headerViewHolder.mTypeRankBtn.setVisibility(View.GONE); headerViewHolder.mTypeMore.setVisibility(View.VISIBLE); headerViewHolder.mAllLiveNum.setVisibility(View.GONE); break; } }
@Override public void bind(Pair<ServerConnectionInfo, String> item) { String name = item.first.getName(); String channel = item.second; int iof = channel.indexOf(mHighlightQuery); SpannableString str = new SpannableString(channel + " " + name); str.setSpan(new ForegroundColorSpan(mHighlightTextColor), iof, iof + mHighlightQuery.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new ForegroundColorSpan(mSecondaryTextColor), channel.length() + 2, channel.length() + 2 + name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); mText.setText(str); }
@Override public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) { HeaderViewHolder viewHolder = (HeaderViewHolder) holder; setTypeIcon(viewHolder); viewHolder.mTypeTv.setText(title); viewHolder.mTypeRankBtn.setOnClickListener(v -> { mContext.startActivity(new Intent(mContext, OriginalRankActivity.class)); }); switch(type){ case TYPE_RECOMMENDED: viewHolder.mTypeMore.setVisibility(View.GONE); viewHolder.mTypeRankBtn.setVisibility(View.VISIBLE); viewHolder.mAllLiveNum.setVisibility(View.GONE); break; case TYPE_LIVE: viewHolder.mTypeMore.setVisibility(View.VISIBLE); viewHolder.mTypeRankBtn.setVisibility(View.GONE); viewHolder.mAllLiveNum.setVisibility(View.VISIBLE); SpannableStringBuilder builder = new SpannableStringBuilder("当前" + liveCount + "个直播"); ForegroundColorSpan colorSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.pink_text_color)); builder.setSpan(colorSpan, 2, builder.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); viewHolder.mAllLiveNum.setText(builder); break; default : viewHolder.mTypeMore.setVisibility(View.VISIBLE); viewHolder.mTypeRankBtn.setVisibility(View.GONE); viewHolder.mAllLiveNum.setVisibility(View.GONE); break; } }
@Override protected boolean verifyDrawable(Drawable drawable) { if (mContainsImages && getText() instanceof Spanned) { Spanned text = (Spanned) getText(); TextInlineImageSpan[] spans = text.getSpans(0, text.length(), TextInlineImageSpan.class); for (TextInlineImageSpan span : spans) { if (span.getDrawable() == drawable) { return true; } } } return super.verifyDrawable(drawable); }
private Builder(@NonNull CharSequence text) { this.text = text; flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE; foregroundColor = defaultValue; backgroundColor = defaultValue; quoteColor = defaultValue; textSize = -1; proportion = -1; xProportion = -1; mBuilder = new SpannableStringBuilder(); }
@SuppressWarnings("deprecation") public static Spanned fromHtml(String source) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY); } else { return Html.fromHtml(source); } }
/** * 设置hint大小 * * @param size * @param v * @param res */ public static void setViewHintSize(Context context, int size, TextView v, int res) { SpannableString ss = new SpannableString(getResources(context).getString( res)); // 新建一个属性对象,设置文字的大小 AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true); // 附加属性到文本 ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置hint v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失 }
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { // If 8 digits have been pasted, replacing all source, trim alpha digits. // Otherwise standard LengthFilter behavior. final int srcLength = end - start; final int dstSelLength = dend - dstart; if (srcLength == PASTED_LEN && dstSelLength == dest.length()) { // Discard alpha digits: return source.subSequence(PASTED_LEN - MAX_LENGTH, PASTED_LEN); } else { return sixDigitFilter.filter(source, start, end, dest, dstart, dend); } }
@Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { try { int input = Integer.parseInt(dest.toString() + source.toString()); if (isInRange(min, max, input)) { return null; } } catch (NumberFormatException nfe) { } return ""; }
/** * Sets span objects to the text. This is more efficient than creating a new instance of Spanny * or SpannableStringBuilder. * @return {@code SpannableString}. */ public static SpannableString spanText(CharSequence text, Object... spans) { SpannableString spannableString = new SpannableString(text); for (Object span : spans) { spannableString.setSpan(span, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannableString; }
private void markPro(Preference pref, String sku) { if (sku == null || !IAB.isPurchased(sku, this)) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean dark = prefs.getBoolean("dark_theme", false); SpannableStringBuilder ssb = new SpannableStringBuilder(" " + pref.getTitle()); ssb.setSpan(new ImageSpan(this, dark ? R.drawable.ic_shopping_cart_white_24dp : R.drawable.ic_shopping_cart_black_24dp), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); pref.setTitle(ssb); } }
/** * 处理关键字高亮 * 如果需要检索算法库,请联系我 * * @param originStr 被处理字符串 * @param keyWord 关键字 * @param hightLightColor 高亮颜色 * @return CharSequence */ public static CharSequence handleKeyWordHighLight (String originStr, String keyWord, @ColorInt int hightLightColor) { SpannableString ss = new SpannableString(originStr); Pattern p = Pattern.compile(keyWord); Matcher m = p.matcher(ss); while (m.find()) { ss.setSpan(new ForegroundColorSpan(hightLightColor), m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return ss; }
@Override public void onStartTemporaryDetach() { super.onStartTemporaryDetach(); if (mContainsImages && getText() instanceof Spanned) { Spanned text = (Spanned) getText(); TextInlineImageSpan[] spans = text.getSpans(0, text.length(), TextInlineImageSpan.class); for (TextInlineImageSpan span : spans) { span.onStartTemporaryDetach(); } } }
@SuppressWarnings("deprecation") public static Spanned fromHtmlCompat(String text) { if (hasNougat()) { return Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY); } else { return Html.fromHtml(text); } }
/** * 显示snackbar */ public void show() { final View view = parent.get(); if (view == null) return; if (messageColor != DEFAULT_COLOR) { SpannableString spannableString = new SpannableString(message); ForegroundColorSpan colorSpan = new ForegroundColorSpan(messageColor); spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); snackbarWeakReference = new WeakReference<>(Snackbar.make(view, spannableString, duration)); } else { snackbarWeakReference = new WeakReference<>(Snackbar.make(view, message, duration)); } final Snackbar snackbar = snackbarWeakReference.get(); final View snackbarView = snackbar.getView(); if (bgResource != -1) { snackbarView.setBackgroundResource(bgResource); } else if (bgColor != DEFAULT_COLOR) { snackbarView.setBackgroundColor(bgColor); } if (bottomMargin != 0) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) snackbarView.getLayoutParams(); params.bottomMargin = bottomMargin; } if (actionText.length() > 0 && actionListener != null) { if (actionTextColor != DEFAULT_COLOR) { snackbar.setActionTextColor(actionTextColor); } snackbar.setAction(actionText, actionListener); } snackbar.show(); }