/** * Combine all of the options that have been set and return a new {@link * net.frakbot.jumpingbeans.JumpingBeans} instance. * * <p>Remember to call the {@link #stopJumping()} method once you're done using the JumpingBeans * (that is, when you detach the TextView from the view tree, you hide it, or the parent * Activity/Fragment goes in the paused status). This will allow to release the animations and * free up memory and CPU that would be otherwise wasted. */ public JumpingBeans build() { SpannableStringBuilder sbb = new SpannableStringBuilder(text); JumpingBeansSpan[] jumpingBeans; if (!wave) { jumpingBeans = new JumpingBeansSpan[] {new JumpingBeansSpan(textView, loopDuration, 0, 0, animRange)}; sbb.setSpan(jumpingBeans[0], startPos, endPos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { if (waveCharDelay == -1) { waveCharDelay = loopDuration / (3 * (endPos - startPos)); } jumpingBeans = 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); jumpingBeans[pos - startPos] = jumpingBean; } } textView.setText(sbb); return new JumpingBeans(jumpingBeans, textView); }
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) { String href = node.getAttributeByName("href"); if (href == null) { return; } final String linkHref = href; // First check if it should be a normal URL link for (String protocol : this.externalProtocols) { if (href.toLowerCase(Locale.US).startsWith(protocol)) { builder.setSpan(new URLSpan(href), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return; } } // If not, consider it an internal nav link. ClickableSpan span = new ClickableSpan() { @Override public void onClick(View widget) { navigateTo(spine.resolveHref(linkHref)); } }; builder.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.verify); ViewUtils.inject(this); // 记录Activity以便退出时全部finish() Const.activityList.add(this); count = new TimeCount(60000, 1000); // 构造CountDownTimer对象 Button goButton = (Button) findViewById(R.id.gobutton); ImageView back = (ImageView) findViewById(R.id.ivAppBack); textState.setTextSize(12); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("点击“手机绑定登陆”,即表示同意《超速洗用户协议》"); ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.parseColor("#28ccfc")); spannableStringBuilder.setSpan( new URLSpan("http://www.baidu.com"), 16, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan( blueSpan, 16, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textState.setMovementMethod(LinkMovementMethod.getInstance()); textState.setText(spannableStringBuilder); }
private void setImageSpan(SpannableStringBuilder builder, Drawable drawable, int start, int end) { builder.setSpan(new ImageSpan(drawable), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (spine.isCover()) { builder.setSpan(new CenterSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } }
/** * 组合消息文本 * * @param name * @param body * @return */ public static SpannableStringBuilder parseFriendPostpan( String name, SpannableStringBuilder body) { SpannableStringBuilder sp = null; int start = 0; int end = 0; String mName = name + ":"; sp = body.insert(0, mName); // sp = new SpannableString(name + ":" + body); end = name.length(); // 设置用户名字体加粗、高亮 sp.setSpan( new StyleSpan(android.graphics.Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sp.setSpan( new ForegroundColorSpan(Color.parseColor("#2f548f")), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sp.setSpan( new ForegroundColorSpan(Color.parseColor("#ff000000")), end, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return sp; }
public static void setNameAndUsername(TextView textView, String name, String username) { Context c = textView.getContext(); ForegroundColorSpan grayTextForegroundSpan = new ForegroundColorSpan(c.getResources().getColor(R.color.name_gray)); AbsoluteSizeSpan fontsizeSpan = new AbsoluteSizeSpan(20); SpannableStringBuilder ssb = new SpannableStringBuilder(name + " @" + username); // Apply the color span ssb.setSpan( grayTextForegroundSpan, // the span to add name.length() + 1, // the start of the span (inclusive) ssb.length(), // the end of the span (exclusive) Spanned .SPAN_EXCLUSIVE_EXCLUSIVE); // behavior when text is later inserted into the // SpannableStringBuilder ssb.setSpan( fontsizeSpan, // the span to add name.length() + 1, // the start of the span (inclusive) ssb.length(), // the end of the span (exclusive) Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(ssb); }
private void updateTitle(Tab tab) { // Keep the title unchanged if there's no selected tab, // or if the tab is entering reader mode. if (tab == null || tab.isEnteringReaderMode()) { return; } final String url = tab.getURL(); // Setting a null title will ensure we just see the // "Enter Search or Address" placeholder text. if (AboutPages.isTitlelessAboutPage(url)) { setTitle(null); return; } // Show the about:blocked page title in red, regardless of prefs if (tab.getErrorType() == Tab.ErrorType.BLOCKED) { final String title = tab.getDisplayTitle(); final SpannableStringBuilder builder = new SpannableStringBuilder(title); builder.setSpan(mBlockedColor, 0, title.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); setTitle(builder); return; } // If the pref to show the title is set, use the tab's display title. if (!mPrefs.shouldShowUrl() || url == null) { setTitle(tab.getDisplayTitle()); return; } String strippedURL = stripAboutReaderURL(url); if (mPrefs.shouldTrimUrls()) { strippedURL = StringUtils.stripCommonSubdomains(StringUtils.stripScheme(strippedURL)); } CharSequence title = strippedURL; final String baseDomain = tab.getBaseDomain(); if (!TextUtils.isEmpty(baseDomain)) { final SpannableStringBuilder builder = new SpannableStringBuilder(title); int index = title.toString().indexOf(baseDomain); if (index > -1) { builder.setSpan(mUrlColor, 0, title.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); builder.setSpan( tab.isPrivate() ? mPrivateDomainColor : mDomainColor, index, index + baseDomain.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); title = builder; } } setTitle(title); }
@Override public void onLoadResource(String href, InputStream input) { Bitmap bitmap = null; try { bitmap = getBitmap(input); if (bitmap == null || bitmap.getHeight() < 1 || bitmap.getWidth() < 1) { return; } } catch (OutOfMemoryError outofmem) { LOG.error("Could not load image", outofmem); } if (bitmap != null) { Drawable drawable = new FastBitmapDrawable(bitmap); drawable.setBounds(0, 0, bitmap.getWidth() - 1, bitmap.getHeight() - 1); builder.setSpan(new ImageSpan(drawable), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (spine.isCover()) { builder.setSpan(new CenterSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } }
public void updateText(@Nullable BidiFormatter formatter) { final SpannableStringBuilder sb = new SpannableStringBuilder(); final String primaryText = mNameFirst ? mName : mScreenName; final String secondaryText = mNameFirst ? mScreenName : mName; if (primaryText != null) { int start = sb.length(); if (formatter != null && !isInEditMode()) { sb.append(formatter.unicodeWrap(primaryText)); } else { sb.append(primaryText); } int end = sb.length(); sb.setSpan(mPrimaryTextColor, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); sb.setSpan(mPrimaryTextStyle, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); sb.setSpan(mPrimaryTextSize, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } sb.append(mTwoLine ? '\n' : ' '); if (secondaryText != null) { int start = sb.length(); if (formatter != null && !isInEditMode()) { sb.append(formatter.unicodeWrap(secondaryText)); } else { sb.append(secondaryText); } int end = sb.length(); sb.setSpan(mSecondaryTextColor, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); sb.setSpan(mSecondaryTextStyle, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); sb.setSpan(mSecondaryTextSize, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } setText(sb); }
/* (non-Javadoc) * manipulates the view for amount (setting expenses to red) and * category (indicate transfer direction with => or <= * @see android.widget.CursorAdapter#getView(int, android.view.View, android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = super.getView(position, convertView, parent); ViewHolder viewHolder = (ViewHolder) convertView.getTag(); TextView tv1 = viewHolder.amount; Cursor c = getCursor(); c.moveToPosition(position); if (mAccount.getId() < 0) { int color = c.getInt(c.getColumnIndex("color")); viewHolder.colorAccount.setBackgroundColor(color); } long amount = c.getLong(columnIndexAmount); setColor(tv1, amount < 0); TextView tv2 = viewHolder.category; CharSequence catText = tv2.getText(); if (DbUtils.getLongOrNull(c, columnIndexTransferPeer) != null) { catText = ((amount < 0) ? "=> " : "<= ") + catText; } else { Long catId = DbUtils.getLongOrNull(c, KEY_CATID); if (SPLIT_CATID.equals(catId)) catText = getString(R.string.split_transaction); else if (catId == null) { catText = getString(R.string.no_category_assigned); } else { String label_sub = c.getString(columnIndexLabelSub); if (label_sub != null && label_sub.length() > 0) { catText = catText + categorySeparator + label_sub; } } } String referenceNumber = c.getString(columnIndexReferenceNumber); if (referenceNumber != null && referenceNumber.length() > 0) catText = "(" + referenceNumber + ") " + catText; SpannableStringBuilder ssb; String comment = c.getString(columnIndexComment); if (comment != null && comment.length() > 0) { ssb = new SpannableStringBuilder(comment); ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, comment.length(), 0); catText = TextUtils.concat(catText, commentSeparator, ssb); } String payee = c.getString(columnIndexPayee); if (payee != null && payee.length() > 0) { ssb = new SpannableStringBuilder(payee); ssb.setSpan(new UnderlineSpan(), 0, payee.length(), 0); catText = TextUtils.concat(catText, commentSeparator, ssb); } tv2.setText(catText); if (!mAccount.type.equals(Type.CASH)) { CrStatus status; try { status = CrStatus.valueOf(c.getString(columnIndexCrStatus)); } catch (IllegalArgumentException ex) { status = CrStatus.UNRECONCILED; } viewHolder.color1.setBackgroundColor(status.color); viewHolder.colorContainer.setTag(status == CrStatus.RECONCILED ? -1 : getItemId(position)); } return convertView; }
/** 显示在输入框的注码 */ public void showEditText() { SpannableStringBuilder builder = new SpannableStringBuilder(); String zhumas = ""; int num = 0; // 高亮小球数 int length = 0; for (int j = 0; j < itemViewArray.get(0).areaNums.length; j++) { BallTable ballTable = itemViewArray.get(0).areaNums[j].table; int[] zhuMa = ballTable.getHighlightBallNOs(); if (j != 0) { if (iCurrentButton == PublicConst.BUY_PL3_ZU3_DAN) { zhumas += ","; } else { zhumas += " | "; } } for (int i = 0; i < ballTable.getHighlightBallNOs().length; i++) { if (isTen) { zhumas += PublicMethod.getZhuMa(zhuMa[i]); } else { zhumas += zhuMa[i] + ""; } if (i != ballTable.getHighlightBallNOs().length - 1) { zhumas += ","; } } num += zhuMa.length; } if (num == 0) { editZhuma.setText(""); } else { builder.append(zhumas); String zhuma[]; if (iCurrentButton == PublicConst.BUY_PL3_ZU3_DAN) { zhuma = zhumas.split("\\,"); } else { zhuma = zhumas.split("\\|"); } for (int i = 0; i < zhuma.length; i++) { if (i != 0) { length += zhuma[i].length() + 1; } else { length += zhuma[i].length(); } if (i != zhuma.length - 1) { builder.setSpan( new ForegroundColorSpan(Color.BLACK), length, length + 1, Spanned.SPAN_COMPOSING); } builder.setSpan( new ForegroundColorSpan(itemViewArray.get(0).areaNums[i].textColor), length - zhuma[i].length(), length, Spanned.SPAN_COMPOSING); } editZhuma.setText(builder, BufferType.EDITABLE); } }
/* * Add size, color and style to a given text */ private static CharSequence addStyle(CharSequence text, int size, int color) { SpannableStringBuilder builder = new SpannableStringBuilder(text); builder.setSpan( new AbsoluteSizeSpan(size), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (color != 0) { builder.setSpan( new ForegroundColorSpan(color), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } return builder; }
/** Parse mIRC style codes in IrcMessage */ public void parseStyleCodes(IrcMessage message) { final char boldIndicator = 2; final char normalIndicator = 15; final char italicIndicator = 29; final char underlineIndicator = 31; String content = message.content.toString(); if (content.indexOf(boldIndicator) == -1 && content.indexOf(italicIndicator) == -1 && content.indexOf(underlineIndicator) == -1) return; SpannableStringBuilder newString = new SpannableStringBuilder(message.content); while (true) { content = newString.toString(); int start = content.indexOf(boldIndicator); int end = content.indexOf(boldIndicator, start + 1); int style = Typeface.BOLD; if (start == -1) { start = content.indexOf(italicIndicator); end = content.indexOf(italicIndicator, start + 1); style = Typeface.ITALIC; } if (start == -1) { start = content.indexOf(underlineIndicator); end = content.indexOf(underlineIndicator, start + 1); style = -1; } if (start == -1) break; if (end == -1) end = content.indexOf(normalIndicator, start); if (end == -1) end = content.length() - 1; if (style == -1) { newString.setSpan(new UnderlineSpan(), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } else { newString.setSpan(new StyleSpan(style), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } if (content.charAt(end) == boldIndicator || content.charAt(end) == italicIndicator || content.charAt(end) == normalIndicator || content.charAt(end) == underlineIndicator) newString.delete(end, end + 1); newString.delete(start, start + 1); } message.content = newString; }
public Spannable formatField(String label, String value, int color1, int color2) { int start = 0; SpannableStringBuilder str = new SpannableStringBuilder(label == null ? "" : label); str.append(": "); int end = str.length(); str.setSpan(new ForegroundColorSpan(color1), start, end, 0); start = end; str.append(value == null ? "" : value); end = str.length(); str.setSpan(new ForegroundColorSpan(color2), start, end, 0); return str; }
private void setBatteryIcon(int level, boolean plugged) { mLevel = level; mPlugged = plugged; ContentResolver cr = mContext.getContentResolver(); mBatteryStyle = Settings.System.getInt(cr, Settings.System.STATUSBAR_BATTERY_ICON, 0); int icon; if (mBatteryStyle == STYLE_ICON_CIRCLE) { icon = plugged ? R.drawable.stat_sys_battery_charge_mod : R.drawable.stat_sys_battery_mod; } else { icon = plugged ? R.drawable.stat_sys_battery_charge : R.drawable.stat_sys_battery; } int N = mIconViews.size(); for (int i = 0; i < N; i++) { ImageView v = mIconViews.get(i); v.setImageResource(icon); v.setImageLevel(level); v.setContentDescription(mContext.getString(R.string.accessibility_battery_level, level)); } N = mLabelViews.size(); for (int i = 0; i < N; i++) { TextView v = mLabelViews.get(i); v.setText(mContext.getString(R.string.status_bar_settings_battery_meter_format, level)); } // do my stuff here if (mBatteryGroup != null) { mBatteryText.setText(Integer.toString(level)); mBatteryCenterText.setText(Integer.toString(level)); mBatteryTextOnly.setText(Integer.toString(level)); SpannableStringBuilder formatted = new SpannableStringBuilder(Integer.toString(level) + "%"); CharacterStyle style = new RelativeSizeSpan(0.7f); // beautiful // formatting if (level < 10) { // level < 10, 2nd char is % formatted.setSpan(style, 1, 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } else if (level < 100) { // level 10-99, 3rd char is % formatted.setSpan(style, 2, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } else { // level 100, 4th char is % formatted.setSpan(style, 3, 4, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } mBatteryTextOnly.setText(formatted); if (plugged) { // colors hardcoded by now, maybe colorpicker can be // added if needed mBatteryTextOnly.setTextColor(Color.GREEN); } else if (level < 16) { mBatteryTextOnly.setTextColor(Color.RED); } else { mBatteryTextOnly.setTextColor(0xFF33B5E5); } } }
/** * Set the necessary spans for each spoiler. * * <p>The algorithm works in the same way as <code>setCodeFont</code>. * * @param sequence * @return */ private CharSequence setSpoilerStyle(SpannableStringBuilder sequence) { int start = 0; int end = 0; for (int i = 0; i < sequence.length(); i++) { if (sequence.charAt(i) == '[' && i < sequence.length() - 3) { if (sequence.charAt(i + 1) == '[' && sequence.charAt(i + 2) == 's' && sequence.charAt(i + 3) == '[') { start = i; } } else if (sequence.charAt(i) == ']' && i < sequence.length() - 3) { if (sequence.charAt(i + 1) == 's' && sequence.charAt(i + 2) == ']' && sequence.charAt(i + 3) == ']') { end = i; } } if (end > start) { sequence.delete(end, end + 4); sequence.delete(start, start + 4); BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.BLACK); ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLACK); URLSpan urlSpan = sequence.getSpans(start, start, URLSpan.class)[0]; sequence.setSpan( urlSpan, sequence.getSpanStart(urlSpan), start - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // spoiler text has a space at the front sequence.setSpan( backgroundColorSpan, start + 1, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); sequence.setSpan(foregroundColorSpan, start, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); storedSpoilerSpans.add(foregroundColorSpan); storedSpoilerSpans.add(backgroundColorSpan); // Shift 1 to account for remove of beginning "<" storedSpoilerStarts.add(start - 1); storedSpoilerStarts.add(start - 1); storedSpoilerEnds.add(end - 5); storedSpoilerEnds.add(end - 5); sequence.delete(start - 2, start - 1); // remove the trailing < start = 0; end = 0; i = i - 5; // move back to compensate for removal of [[s[ } } return sequence; }
public static SpannableStringBuilder changeTextPartColor( String text, int start, int end, int start2, int end2, int color) { if (text == null) { return new SpannableStringBuilder(""); } SpannableStringBuilder style = new SpannableStringBuilder(text); // //设置指定位置的背景颜色 // style.setSpan(new // BackgroundColorSpan(Color.RED),0,4,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); // 设置指定位置的文字颜色 style.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); style.setSpan(new ForegroundColorSpan(color), start2, end2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); return style; }
private SpannableStringBuilder doAutoLinks( SpannableStringBuilder ssb, ArrayList<MarkdownURL> urls) { // Colorize URLs AutomatonMatcher am = autoLinkUrlAutomaton.newMatcher(ssb); while (am.find()) { ForegroundColorSpan fcs = new ForegroundColorSpan(Constants.MARKDOWN_LINK_COLOR); ssb.setSpan(fcs, am.start(), am.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); urls.add(new MarkdownURL(am.start(), am.group(), null)); } // Don't autolink emails for now. Neither does reddit.com // m = autoLinkEmail.matcher(ssb); // int start = 0; // while (m.find(start)) { // String address = m.group(1); // TextEditor ed = new TextEditor(address); // unEscapeSpecialChars(ed); // String addr = encodeEmail(ed.toString()); // String url = encodeEmail("mailto:" + ed.toString()); // // urls.add(url); // ssb.replace(m.start(), m.end(), addr); // ForegroundColorSpan fcs = new ForegroundColorSpan(Constants.MARKDOWN_LINK_COLOR); // ssb.setSpan(fcs, m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // // Skip what we just replaced // m = autoLinkEmail.matcher(ssb); // start = m.start() + addr.length(); // } return ssb; }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tv = new TextView(this); ctx = this; String htmlLinkText = "我是超链接" + "<a href='lianjie'><font color='red'>超链接点击事件</font></a>"; // 文字的样式(style)被覆盖,不能改变…… tv.setText(Html.fromHtml(htmlLinkText)); tv.setMovementMethod(LinkMovementMethod.getInstance()); CharSequence text = tv.getText(); if (text instanceof Spannable) { int end = text.length(); Spannable sp = (Spannable) tv.getText(); URLSpan[] urls = sp.getSpans(0, end, URLSpan.class); SpannableStringBuilder style = new SpannableStringBuilder(text); style.clearSpans(); // should clear old spans // 循环把链接发过去 for (URLSpan url : urls) { MyURLSpan myURLSpan = new MyURLSpan(url.getURL()); style.setSpan( myURLSpan, sp.getSpanStart(url), sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } tv.setText(style); } setContentView(tv); }
public void setSpecifiedTextsColor(String text, String specifiedTexts, int color) { List<Integer> sTextsStartList = new ArrayList<>(); int sTextLength = specifiedTexts.length(); String temp = text; int lengthFront = 0; // 记录被找出后前面的字段的长度 int start = -1; do { start = temp.indexOf(specifiedTexts); if (start != -1) { start = start + lengthFront; sTextsStartList.add(start); lengthFront = start + sTextLength; temp = text.substring(lengthFront); } } while (start != -1); SpannableStringBuilder styledText = new SpannableStringBuilder(text); for (Integer i : sTextsStartList) { styledText.setSpan( new ForegroundColorSpan(color), i, i + sTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } setText(styledText); }
/** * 组合回复引用文本 * * @param name * @param body * @return */ public static SpannableStringBuilder parseQuoteSpan(String name, SpannableStringBuilder body) { String nName = "回复:" + name + "\n"; SpannableStringBuilder sp = body.insert(0, nName); // 设置用户名字体加粗、高亮 sp.setSpan( new StyleSpan(android.graphics.Typeface.BOLD), 3, nName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sp.setSpan( new ForegroundColorSpan(Color.parseColor("#0e5986")), 3, nName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return sp; }
private void geckoActionReply() { if (DEBUG) { // GeckoEditableListener methods should all be called from the Gecko thread ThreadUtils.assertOnGeckoThread(); } final Action action = mActionQueue.peek(); if (action == null) { throw new IllegalStateException("empty actions queue"); } if (DEBUG) { Log.d(LOGTAG, "reply: Action(" + getConstantName(Action.class, "TYPE_", action.mType) + ")"); } switch (action.mType) { case Action.TYPE_SET_SELECTION: final int len = mText.length(); final int curStart = Selection.getSelectionStart(mText); final int curEnd = Selection.getSelectionEnd(mText); // start == -1 when the start offset should remain the same // end == -1 when the end offset should remain the same final int selStart = Math.min(action.mStart < 0 ? curStart : action.mStart, len); final int selEnd = Math.min(action.mEnd < 0 ? curEnd : action.mEnd, len); if (selStart < action.mStart || selEnd < action.mEnd) { Log.w(LOGTAG, "IME sync error: selection out of bounds"); } Selection.setSelection(mText, selStart, selEnd); geckoPostToIc( new Runnable() { @Override public void run() { mActionQueue.syncWithGecko(); final int start = Selection.getSelectionStart(mText); final int end = Selection.getSelectionEnd(mText); if (selStart == start && selEnd == end) { // There has not been another new selection in the mean time that // made this notification out-of-date mListener.onSelectionChange(start, end); } } }); break; case Action.TYPE_SET_SPAN: mText.setSpan(action.mSpanObject, action.mStart, action.mEnd, action.mSpanFlags); break; case Action.TYPE_REMOVE_SPAN: mText.removeSpan(action.mSpanObject); break; case Action.TYPE_SET_HANDLER: geckoSetIcHandler(action.mHandler); break; } if (action.mShouldUpdate) { geckoUpdateGecko(false); } }
@Override public void onBindViewHolder(MyViewHolder holder, int position) { Note note = mNoteList.get(position); holder.tvNoteTitle.setText(note.getTitle()); String time = note.getTime(); // reformat date to "dd/mm/yyyy" Date date = DateUtils.stringToDate(time); SimpleDateFormat fomatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); String newTime = fomatter.format(date); String content = note.getContent(); String newContent = newTime + " " + content; // change time's color in textview SpannableStringBuilder style = new SpannableStringBuilder(newContent); style.setSpan( new ForegroundColorSpan(getResources().getColor(R.color.jikelv)), 0, newTime.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE); holder.tvNoteContent.setText(style); String imagePath = note.getImagePath(); if (!TextUtils.isEmpty(imagePath)) { mBitmapUtils.display(holder.ivPhoto, imagePath); holder.ivPhoto.setVisibility(View.VISIBLE); } else { holder.ivPhoto.setVisibility(View.GONE); } }
/** 设置颜色 */ public void setResultColor(String checkName, String name, TextView result) { SpannableStringBuilder builder = new SpannableStringBuilder(); int start = name.indexOf(checkName); int max = name.length(); endMax = restrictMax; for (int i = 0; i < restrictMax; i++) { // 循环遍历字符串 if (Pattern.compile("(?i)[a-z]").matcher(name).find() || Pattern.compile("(?i)[A-Z]").matcher(name).find()) { // 用char包装类中的判断数字的方法判断每一个字符 endMax++; } } if (max > endMax) { name = name.substring(0, endMax); for (int i = 0; i < max - endMax; i++) { name += "."; } } builder.append(name); if (!checkName.equals("")) { builder.setSpan( new ForegroundColorSpan(Color.RED), start, start + checkName.length(), Spanned.SPAN_COMPOSING); } result.setText(builder, BufferType.EDITABLE); }
Spannable diffSpannable(LinkedList<SyncTextDiff> diffs) { SpannableStringBuilder result = new SpannableStringBuilder(); int start; String text; int color = Color.YELLOW; for (SyncTextDiff diff : diffs) { start = result.length(); text = diff.text; switch (diff.operation) { case SyncTextDiff.DELETE: result.append(text, new BackgroundColorSpan(color), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); result.setSpan( new StrikethroughSpan(), start, start + text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); break; case SyncTextDiff.INSERT: result.append(text, new BackgroundColorSpan(color), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); break; case SyncTextDiff.EQUAL: result.append(text); break; } } return result; }
/** * 关键字高亮显示 * * @param target 需要高亮的关键字 * @param text 需要显示的文字 * @param foregroundColor 高亮文字的前景颜色 * @param backgroundColor 高亮文字的背景颜色 * @return spannable 处理完后的结果,记得不要toString(),否则没有效果 */ public static SpannableStringBuilder highLight( String text, String target, int foregroundColor, int backgroundColor) { SpannableStringBuilder spannable = new SpannableStringBuilder(text); CharacterStyle span = null; Pattern p = Pattern.compile(target); Matcher m = p.matcher(text); while (m.find()) { span = new ForegroundColorSpan(foregroundColor); // 需要重复! spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); span = new BackgroundColorSpan(backgroundColor); // 需要重复! spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannable; }
public MDFormatter(List<Markdown.MDLine> lines) { for (Markdown.MDLine line : lines) { format(line); } mBuilder.setSpan( new TypefaceSpan("monospace"), 0, mBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); }
/** * Sets the styling for string with code segments. * * <p>The general process is to search for <code>[[<[</code> and <code>]>]]</code> tokens to * find the code fragments within the escaped text. A <code>Spannable</code> is created which * which breaks up the origin sequence into non-code and code fragments, and applies a monospace * font to the code fragments. * * @param sequence the Spannable generated from Html.fromHtml * @return the message with monospace font applied to code fragments */ private CharSequence setCodeFont(SpannableStringBuilder sequence) { int start = 0; int end = 0; for (int i = 0; i < sequence.length(); i++) { if (sequence.charAt(i) == '[' && i < sequence.length() - 3) { if (sequence.charAt(i + 1) == '[' && sequence.charAt(i + 2) == '<' && sequence.charAt(i + 3) == '[') { start = i; } } else if (sequence.charAt(i) == ']' && i < sequence.length() - 3) { if (sequence.charAt(i + 1) == '>' && sequence.charAt(i + 2) == ']' && sequence.charAt(i + 3) == ']') { end = i; } } if (end > start) { sequence.delete(end, end + 4); sequence.delete(start, start + 4); sequence.setSpan( new TypefaceSpan("monospace"), start, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); start = 0; end = 0; i = i - 4; // move back to compensate for removal of [[<[ } } return sequence; }
public static void tryFlowText( SpannableStringBuilder ss, View thumbnailView, TextView messageView, Display display) { // There is nothing I can do for older versions, so just return if (!mNewClassAvailable) return; // Get height and width of the image and height of the text line thumbnailView.measure(display.getWidth(), display.getHeight()); int height = thumbnailView.getMeasuredHeight(); int width = thumbnailView.getMeasuredWidth(); float textLineHeight = messageView.getPaint().getTextSize(); // Set the span according to the number of lines and width of the image int lines = (int) Math.round(height / textLineHeight); // For an html text you can use this line: SpannableStringBuilder ss = // (SpannableStringBuilder)Html.fromHtml(text); ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), 0); messageView.setText(ss); // Align the text with the image by removing the rule that the text is // to the right of the image RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) messageView.getLayoutParams(); int[] rules = params.getRules(); rules[RelativeLayout.RIGHT_OF] = 0; }
private String getCustomValuesText(PDroidAppSetting setting) { if (setting.getCustomValues() != null && setting.getCustomValues().size() > 0) { List<String> customValueStrings = new LinkedList<String>(); for (SimpleImmutableEntry<String, String> customValue : setting.getCustomValues()) { SpannableStringBuilder builder = new SpannableStringBuilder(); if (customValue.getKey() != null && !(customValue.getKey().isEmpty())) { builder.append(customValue.getKey()).append(":"); } if (customValue.getValue() != null && !(customValue.getValue().isEmpty())) { builder.append(customValue.getValue()); builder.setSpan( new StyleSpan(Typeface.ITALIC), builder.length() - customValue.getValue().length(), builder.length(), 0); } if (!builder.toString().isEmpty()) { customValueStrings.add(builder.toString()); } } if (customValueStrings.size() > 0) { return TextUtils.join( context.getString(R.string.detail_custom_value_spacer), customValueStrings); } } return null; }