Java Code Examples for android.text.style.StyleSpan

The following are top voted examples for showing how to use android.text.style.StyleSpan. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: q-mail   File: MessageHeader.java   Source Code and License 6 votes vote down vote up
/**
 * Set up the additional headers text view with the supplied header data.
 *
 * @param additionalHeaders List of header entries. Each entry consists of a header
 *                          name and a header value. Header names may appear multiple
 *                          times.
 *                          <p/>
 *                          This method is always called from within the UI thread by
 *                          {@link #showAdditionalHeaders()}.
 */
private void populateAdditionalHeadersView(final List<HeaderEntry> additionalHeaders) {
    SpannableStringBuilder sb = new SpannableStringBuilder();
    boolean first = true;
    for (HeaderEntry additionalHeader : additionalHeaders) {
        if (!first) {
            sb.append("\n");
        } else {
            first = false;
        }
        StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
        SpannableString label = new SpannableString(additionalHeader.label + ": ");
        label.setSpan(boldSpan, 0, label.length(), 0);
        sb.append(label);
        sb.append(MimeUtility.unfoldAndDecode(additionalHeader.value));
    }
    mAdditionalHeadersView.setText(sb);
}
 
Example 2
Project: GitHub   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Sets a spannable text with any highlight color into the provided TextView.
 *
 * @param textView     the TextView to transform
 * @param originalText the original text which the transformation is applied to
 * @param constraint   the text to highlight
 * @param color        the highlight color
 * @see #fetchAccentColor(Context, int)
 * @see #highlightText(TextView, String, String)
 * @since 5.0.0-rc1
 */
public static void highlightText(@NonNull TextView textView, @Nullable String originalText,
								 @Nullable String constraint, @ColorInt int color) {
	if (originalText == null) originalText = "";
	if (constraint == null) constraint = "";
	int i = originalText.toLowerCase(Locale.getDefault()).indexOf(constraint.toLowerCase(Locale.getDefault()));
	if (i != -1) {
		Spannable spanText = Spannable.Factory.getInstance().newSpannable(originalText);
		spanText.setSpan(new ForegroundColorSpan(color), i,
				i + constraint.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		spanText.setSpan(new StyleSpan(Typeface.BOLD), i,
				i + constraint.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		textView.setText(spanText, TextView.BufferType.SPANNABLE);
	} else {
		textView.setText(originalText, TextView.BufferType.NORMAL);
	}
}
 
Example 3
Project: PeSanKita-android   File: MessageNotifier.java   Source Code and License 6 votes vote down vote up
private static void appendPushNotificationState(@NonNull Context context,
                                                @NonNull NotificationState notificationState,
                                                @NonNull Cursor cursor)
{
  PushDatabase.Reader reader = null;
  SignalServiceEnvelope envelope;

  try {
    reader = DatabaseFactory.getPushDatabase(context).readerFor(cursor);

    while ((envelope = reader.getNext()) != null) {
      Recipients      recipients = RecipientFactory.getRecipientsFromString(context, envelope.getSource(), false);
      Recipient       recipient  = recipients.getPrimaryRecipient();
      long            threadId   = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
      SpannableString body       = new SpannableString(context.getString(R.string.MessageNotifier_locked_message));
      body.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, body.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

      if (!recipients.isMuted()) {
        notificationState.addNotification(new NotificationItem(recipient, recipients, null, threadId, body, 0, null));
      }
    }
  } finally {
    if (reader != null)
      reader.close();
  }
}
 
Example 4
Project: PeSanKita-android   File: FromTextView.java   Source Code and License 6 votes vote down vote up
public void setText(Recipients recipients, boolean read) {
  int        attributes[] = new int[]{R.attr.conversation_list_item_count_color};
  TypedArray colors       = getContext().obtainStyledAttributes(attributes);
  String     fromString   = recipients.toShortString();

  int typeface;

  if (!read) {
    typeface = Typeface.BOLD;
  } else {
    typeface = Typeface.NORMAL;
  }

  SpannableStringBuilder builder = new SpannableStringBuilder(fromString);
  builder.setSpan(new StyleSpan(typeface), 0, builder.length(),
                  Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

  colors.recycle();

  setText(builder);

  if      (recipients.isBlocked()) setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_block_grey600_18dp, 0, 0, 0);
  else if (recipients.isMuted())   setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_volume_off_grey600_18dp, 0, 0, 0);
  else                             setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
 
Example 5
Project: airgram   File: WebvttCueParser.java   Source Code and License 6 votes vote down vote up
private static void applySpansForTag(StartTag startTag, SpannableStringBuilder spannedText) {
  switch(startTag.name) {
    case TAG_BOLD:
      spannedText.setSpan(new StyleSpan(STYLE_BOLD), startTag.position,
          spannedText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      return;
    case TAG_ITALIC:
      spannedText.setSpan(new StyleSpan(STYLE_ITALIC), startTag.position,
          spannedText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      return;
    case TAG_UNDERLINE:
      spannedText.setSpan(new UnderlineSpan(), startTag.position,
          spannedText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      return;
    default:
      break;
  }
}
 
Example 6
Project: CSipSimple   File: SipNotifications.java   Source Code and License 6 votes vote down vote up
protected static CharSequence buildTickerMessage(Context context, String address, String body) {
	String displayAddress = address;

	StringBuilder buf = new StringBuilder(displayAddress == null ? "" : displayAddress.replace('\n', ' ').replace('\r', ' '));
	buf.append(':').append(' ');

	int offset = buf.length();

	if (!TextUtils.isEmpty(body)) {
		body = body.replace('\n', ' ').replace('\r', ' ');
		buf.append(body);
	}

	SpannableString spanText = new SpannableString(buf.toString());
	spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, offset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

	return spanText;
}
 
Example 7
Project: Cable-Android   File: FromTextView.java   Source Code and License 6 votes vote down vote up
public void setText(Recipients recipients, boolean read) {
  int        attributes[] = new int[]{R.attr.conversation_list_item_count_color};
  TypedArray colors       = getContext().obtainStyledAttributes(attributes);
  String     fromString   = recipients.toShortString();

  int typeface;

  if (!read) {
    typeface = Typeface.BOLD;
  } else {
    typeface = Typeface.NORMAL;
  }

  SpannableStringBuilder builder = new SpannableStringBuilder(fromString);
  builder.setSpan(new StyleSpan(typeface), 0, builder.length(),
                  Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

  colors.recycle();

  setText(builder);

  if      (recipients.isBlocked()) setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_block_grey600_18dp, 0, 0, 0);
  else if (recipients.isMuted())   setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_volume_off_grey600_18dp, 0, 0, 0);
  else                             setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
 
Example 8
Project: chromium-for-android-56-debug-video   File: PaymentRequestSection.java   Source Code and License 6 votes vote down vote up
/**
 * Builds a CharSequence that displays a value in a particular currency.
 *
 * @param currency    Currency of the value being displayed.
 * @param value       Value to display.
 * @param isValueBold Whether or not to bold the item.
 * @return CharSequence that represents the whole value.
 */
private CharSequence createValueString(String currency, String value, boolean isValueBold) {
    SpannableStringBuilder valueBuilder = new SpannableStringBuilder();
    valueBuilder.append(currency);
    valueBuilder.append(" ");

    int boldStartIndex = valueBuilder.length();
    valueBuilder.append(value);

    if (isValueBold) {
        valueBuilder.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), boldStartIndex,
                boldStartIndex + value.length(), 0);
    }

    return valueBuilder;
}
 
Example 9
Project: chromium-for-android-56-debug-video   File: SuggestionView.java   Source Code and License 6 votes vote down vote up
private boolean applyHighlightToMatchRegions(
        Spannable str, List<MatchClassification> classifications) {
    boolean hasMatch = false;
    for (int i = 0; i < classifications.size(); i++) {
        MatchClassification classification = classifications.get(i);
        if ((classification.style & MatchClassificationStyle.MATCH)
                == MatchClassificationStyle.MATCH) {
            int matchStartIndex = classification.offset;
            int matchEndIndex;
            if (i == classifications.size() - 1) {
                matchEndIndex = str.length();
            } else {
                matchEndIndex = classifications.get(i + 1).offset;
            }
            matchStartIndex = Math.min(matchStartIndex, str.length());
            matchEndIndex = Math.min(matchEndIndex, str.length());

            hasMatch = true;
            // Bold the part of the URL that matches the user query.
            str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
                    matchStartIndex, matchEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return hasMatch;
}
 
Example 10
Project: letv   File: StarActivity.java   Source Code and License 6 votes vote down vote up
private void drawFollowNum(long num) {
    LogInfo.log("clf", "drawFollowNum....num=" + num);
    String followNum = StringUtils.getPlayCountsToStr(num);
    if (TextUtils.isEmpty(followNum)) {
        this.mFollowNum.setText("0");
        return;
    }
    String unit = "";
    String lastChar = followNum.substring(followNum.length() - 1);
    if (!StringUtils.isInt(lastChar)) {
        unit = " " + lastChar;
        followNum = followNum.substring(0, followNum.length() - 1) + unit;
    }
    int start = followNum.length() - unit.length();
    int end = followNum.length();
    SpannableStringBuilder sb = new SpannableStringBuilder(followNum);
    sb.setSpan(new StyleSpan(1), 0, start, 33);
    sb.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(2131165476)), start, end, 33);
    this.mFollowNum.setText(sb);
}
 
Example 11
Project: iosched-reader   File: SearchSnippet.java   Source Code and License 6 votes vote down vote up
@Override
public void setText(CharSequence text, BufferType type) {
    if (!TextUtils.isEmpty(text)) {
        Matcher matcher = PATTERN_SEARCH_TERM.matcher(text);
        SpannableStringBuilder ssb = new SpannableStringBuilder(text);
        List<String> hits = new ArrayList<>();
        while (matcher.find()) {
            hits.add(matcher.group(1));
        }

        for (String hit : hits) {
            int start = ssb.toString().indexOf(hit);
            int end = start + hit.length();
            ssb.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0);
            // delete the markup tokens
            ssb.delete(end - 1, end);
            ssb.delete(start, start + 1);
        }
        text = ssb;
    }
    super.setText(text, type);
}
 
Example 12
Project: iosched-reader   File: UIUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Given a snippet string with matching segments surrounded by curly
 * braces, turn those areas into bold spans, removing the curly braces.
 */
public static Spannable buildStyledSnippet(String snippet) {
    final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);

    // Walk through string, inserting bold snippet spans
    int startIndex, endIndex = -1, delta = 0;
    while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
        endIndex = snippet.indexOf('}', startIndex);

        // Remove braces from both sides
        builder.delete(startIndex - delta, startIndex - delta + 1);
        builder.delete(endIndex - delta - 1, endIndex - delta);

        // Insert bold style
        builder.setSpan(new StyleSpan(Typeface.BOLD),
                startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //builder.setSpan(new ForegroundColorSpan(0xff111111),
        //        startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        delta += 2;
    }

    return builder;
}
 
Example 13
Project: OSchina_resources_android   File: RichEditText.java   Source Code and License 6 votes vote down vote up
void setBold(boolean isBold) {
    int index = getSelectionIndex();
    if (index >= 0 && index < mSections.size()) {
        mSections.get(index).setBold(isBold);
    }
    Editable edit = getEditableText();
    int star = getSectionStart();
    int end = getSectionEnd();
    if (isBold) {
        edit.setSpan(new StyleSpan(Typeface.BOLD),
                star,
                end,
                Typeface.BOLD);
    } else {
        StyleSpan[] styleSpans = edit.getSpans(star,
                end, StyleSpan.class);
        for (CharacterStyle span : styleSpans) {
            if (span instanceof StyleSpan && ((StyleSpan) span).getStyle() == Typeface.BOLD)
                edit.removeSpan(span);
        }
    }
}
 
Example 14
Project: OSchina_resources_android   File: RichEditText.java   Source Code and License 6 votes vote down vote up
void setItalic(boolean isItalic) {
    int index = getSelectionIndex();
    if (index >= 0 && index < mSections.size()) {
        mSections.get(index).setItalic(isItalic);
    }
    Editable edit = getEditableText();
    int star = getSectionStart();
    int end = getSectionEnd();
    if (isItalic) {
        edit.setSpan(new StyleSpan(Typeface.ITALIC),
                star,
                end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        StyleSpan[] styleSpans = edit.getSpans(star,
                end, StyleSpan.class);
        for (CharacterStyle span : styleSpans) {
            if (span instanceof StyleSpan && ((StyleSpan) span).getStyle() == Typeface.ITALIC)
                edit.removeSpan(span);
        }
    }
}
 
Example 15
Project: OSchina_resources_android   File: RichEditText.java   Source Code and License 6 votes vote down vote up
void setItalic(boolean isItalic, int index) {
    if (index >= 0 && index < mSections.size()) {
        mSections.get(index).setItalic(isItalic);
    }
    Editable edit = getEditableText();
    int star = getSectionStart();
    int end = getSectionEnd();
    if (isItalic) {
        edit.setSpan(new StyleSpan(Typeface.ITALIC),
                star,
                end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        StyleSpan[] styleSpans = edit.getSpans(star,
                end, StyleSpan.class);
        for (CharacterStyle span : styleSpans) {
            if (span instanceof StyleSpan && ((StyleSpan) span).getStyle() == Typeface.ITALIC)
                edit.removeSpan(span);
        }
    }
}
 
Example 16
Project: OSchina_resources_android   File: RichEditText.java   Source Code and License 6 votes vote down vote up
void setBold(boolean isBold, int index) {
    if (index >= 0 && index < mSections.size()) {
        mSections.get(index).setBold(isBold);
    }
    Editable edit = getEditableText();
    int star = getSectionStart(index);
    int end = getSectionEnd(index);
    if (star >= end)
        return;
    if (isBold) {
        edit.setSpan(new StyleSpan(Typeface.BOLD),
                star,
                end,
                Typeface.BOLD);
    } else {
        StyleSpan[] styleSpans = edit.getSpans(star,
                end, StyleSpan.class);
        for (CharacterStyle span : styleSpans) {
            if (span instanceof StyleSpan && ((StyleSpan) span).getStyle() == Typeface.BOLD)
                edit.removeSpan(span);
        }
    }
}
 
Example 17
Project: PlusGram   File: WebvttCueParser.java   Source Code and License 6 votes vote down vote up
private static void applySpansForTag(StartTag startTag, SpannableStringBuilder spannedText) {
  switch(startTag.name) {
    case TAG_BOLD:
      spannedText.setSpan(new StyleSpan(STYLE_BOLD), startTag.position,
          spannedText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      return;
    case TAG_ITALIC:
      spannedText.setSpan(new StyleSpan(STYLE_ITALIC), startTag.position,
          spannedText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      return;
    case TAG_UNDERLINE:
      spannedText.setSpan(new UnderlineSpan(), startTag.position,
          spannedText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      return;
    default:
      break;
  }
}
 
Example 18
Project: okwallet   File: WalletTransactionsFragment.java   Source Code and License 6 votes vote down vote up
@Override
public void onLoadFinished(final Loader<List<Transaction>> loader, final List<Transaction> transactions) {
    final Direction direction = ((TransactionsLoader) loader).getDirection();

    adapter.replace(transactions);

    if (transactions.isEmpty()) {
        viewGroup.setDisplayedChild(1);

        final SpannableStringBuilder emptyText = new SpannableStringBuilder(
                getString(direction == Direction.SENT ? R.string.wallet_transactions_fragment_empty_text_sent
                        : R.string.wallet_transactions_fragment_empty_text_received));
        emptyText.setSpan(new StyleSpan(Typeface.BOLD), 0, emptyText.length(),
                SpannableStringBuilder.SPAN_POINT_MARK);
        if (direction != Direction.SENT)
            emptyText.append("\n\n").append(getString(R.string.wallet_transactions_fragment_empty_text_howto));
        emptyView.setText(emptyText);
    } else {
        viewGroup.setDisplayedChild(2);
    }
}
 
Example 19
Project: revolution-irc   File: MessageFormatSettingsActivity.java   Source Code and License 6 votes vote down vote up
public static SpannableString buildActionPresetMessageFormat(Context context, int preset, boolean mention) {
    if (preset == 0 || preset == 1) {
        SpannableString spannable = new SpannableString("  |*    ");
        spannable.setSpan(new MessageBuilder.MetaForegroundColorSpan(context, MessageBuilder.MetaForegroundColorSpan.COLOR_TIMESTAMP), 0, 1, MessageBuilder.FORMAT_SPAN_FLAGS);
        if (preset == 0)
            spannable.setSpan(new StyleSpan(Typeface.ITALIC), 3, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        spannable.setSpan(new MessageBuilder.MetaChipSpan(context, MessageBuilder.MetaChipSpan.TYPE_TIME), 0, 1, MessageBuilder.FORMAT_SPAN_FLAGS);
        spannable.setSpan(new MessageBuilder.MetaChipSpan(context, MessageBuilder.MetaChipSpan.TYPE_SENDER), 5, 6, MessageBuilder.FORMAT_SPAN_FLAGS);
        spannable.setSpan(new MessageBuilder.MetaChipSpan(context, MessageBuilder.MetaChipSpan.TYPE_MESSAGE),  7, 8, MessageBuilder.FORMAT_SPAN_FLAGS);
        spannable.setSpan(new MessageBuilder.MetaChipSpan(context, MessageBuilder.MetaChipSpan.TYPE_WRAP_ANCHOR), 2, 3, MessageBuilder.FORMAT_SPAN_FLAGS);
        if (mention) {
            spannable.setSpan(new StyleSpan(Typeface.BOLD), 5, 6, MessageBuilder.FORMAT_SPAN_FLAGS);
            spannable.setSpan(new MessageBuilder.MetaForegroundColorSpan(context, MessageBuilder.MetaForegroundColorSpan.COLOR_SENDER),  3, 8, MessageBuilder.FORMAT_SPAN_FLAGS);
        } else {
            spannable.setSpan(new MessageBuilder.MetaForegroundColorSpan(context, MessageBuilder.MetaForegroundColorSpan.COLOR_STATUS), 3, 4, MessageBuilder.FORMAT_SPAN_FLAGS);
            spannable.setSpan(new MessageBuilder.MetaForegroundColorSpan(context, MessageBuilder.MetaForegroundColorSpan.COLOR_SENDER), 5, 6, MessageBuilder.FORMAT_SPAN_FLAGS);
        }
        return spannable;
    }
    return null;
}
 
Example 20
Project: revolution-irc   File: SpannableStringHelper.java   Source Code and License 6 votes vote down vote up
public static JsonObject spanToJson(Object span) {
    JsonObject ret = new JsonObject();
    if (span instanceof ForegroundColorSpan) {
        ret.addProperty("type", SPAN_TYPE_FOREGROUND);
        ret.addProperty("color", ((ForegroundColorSpan) span).getForegroundColor());
    } else if (span instanceof BackgroundColorSpan) {
        ret.addProperty("type", SPAN_TYPE_BACKGROUND);
        ret.addProperty("color", ((BackgroundColorSpan) span).getBackgroundColor());
    } else if (span instanceof StyleSpan) {
        ret.addProperty("type", SPAN_TYPE_STYLE);
        ret.addProperty("style", ((StyleSpan) span).getStyle());
    } else {
        return null;
    }
    return ret;
}
 
Example 21
Project: GitHub   File: PiePolylineChartActivity.java   Source Code and License 5 votes vote down vote up
private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.5f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.65f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }
 
Example 22
Project: GitHub   File: HalfPieChartActivity.java   Source Code and License 5 votes vote down vote up
private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }
 
Example 23
Project: GitHub   File: RealmDatabaseActivityPie.java   Source Code and License 5 votes vote down vote up
private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("Realm.io\nmobile database");
        s.setSpan(new ForegroundColorSpan(Color.rgb(240, 115, 126)), 0, 8, 0);
        s.setSpan(new RelativeSizeSpan(2.2f), 0, 8, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), 9, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), 9, s.length(), 0);
        s.setSpan(new RelativeSizeSpan(0.85f), 9, s.length(), 0);
        return s;
    }
 
Example 24
Project: GitHub   File: PieChartActivity.java   Source Code and License 5 votes vote down vote up
private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }
 
Example 25
Project: Espresso   File: CompanyDetailFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void setCompanyName(String name) {
    String companyName = getString(R.string.company_name) + "\n" + name;
    Spannable spannable = new SpannableStringBuilder(companyName);
    spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, companyName.length() - name.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new StyleSpan(Typeface.NORMAL), companyName.length() - name.length(), companyName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textViewCompanyName.setText(spannable);
}
 
Example 26
Project: Espresso   File: CompanyDetailFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void setCompanyTel(String tel) {
    this.tel = tel;
    String companyTel = getString(R.string.phone_number) + "\n" + tel;
    Spannable spannable = new SpannableStringBuilder(companyTel);
    spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, companyTel.length() - tel.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new URLSpan(tel), companyTel.length() - tel.length(), companyTel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textViewTel.setText(spannable);
}
 
Example 27
Project: Espresso   File: CompanyDetailFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void setCompanyWebsite(String website) {
    this.website = website;
    String ws = getString(R.string.official_website) + "\n" + website;
    Spannable spannable = new SpannableStringBuilder(ws);
    spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, ws.length() - website.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new URLSpan(website), ws.length() - website.length(), ws.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textViewWebsite.setText(spannable);
}
 
Example 28
Project: mapbox-navigation-android   File: TimeUtils.java   Source Code and License 5 votes vote down vote up
public static SpannableStringBuilder formatTimeRemaining(double routeDuration) {
  long seconds = (long) routeDuration;

  if (seconds < 0) {
    throw new IllegalArgumentException("Duration must be greater than zero.");
  }

  long days = TimeUnit.SECONDS.toDays(seconds);
  seconds -= TimeUnit.DAYS.toSeconds(days);
  long hours = TimeUnit.SECONDS.toHours(seconds);
  seconds -= TimeUnit.HOURS.toSeconds(hours);
  long minutes = TimeUnit.SECONDS.toMinutes(seconds);
  seconds -= TimeUnit.MINUTES.toSeconds(minutes);

  if (seconds >= 30) {
    minutes = minutes + 1;
  }

  List<SpanItem> spanItems = new ArrayList<>();
  if (days != 0) {
    String dayFormat = days > 1 ? DAYS : DAY;
    spanItems.add(new SpanItem(new StyleSpan(Typeface.BOLD), String.valueOf(days)));
    spanItems.add(new SpanItem(new RelativeSizeSpan(1f), dayFormat));
  }
  if (hours != 0) {
    spanItems.add(new SpanItem(new StyleSpan(Typeface.BOLD), String.valueOf(hours)));
    spanItems.add(new SpanItem(new RelativeSizeSpan(1f), HOUR));
  }
  if (minutes != 0) {
    spanItems.add(new SpanItem(new StyleSpan(Typeface.BOLD), String.valueOf(minutes)));
    spanItems.add(new SpanItem(new RelativeSizeSpan(1f), MINUTE));
  }
  if (days == 0 && hours == 0 && minutes == 0) {
    spanItems.add(new SpanItem(new StyleSpan(Typeface.BOLD), String.valueOf(1)));
    spanItems.add(new SpanItem(new RelativeSizeSpan(1f), MINUTE));
  }

  return SpanUtils.combineSpans(spanItems);
}
 
Example 29
Project: keepass2android   File: SearchBookContentsListItem.java   Source Code and License 5 votes vote down vote up
public void set(SearchBookContentsResult result) {
  pageNumberView.setText(result.getPageNumber());
  String snippet = result.getSnippet();
  if (snippet.isEmpty()) {
    snippetView.setText("");
  } else {
    if (result.getValidSnippet()) {
      String lowerQuery = SearchBookContentsResult.getQuery().toLowerCase(Locale.getDefault());
      String lowerSnippet = snippet.toLowerCase(Locale.getDefault());
      Spannable styledSnippet = new SpannableString(snippet);
      StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
      int queryLength = lowerQuery.length();
      int offset = 0;
      while (true) {
        int pos = lowerSnippet.indexOf(lowerQuery, offset);
        if (pos < 0) {
          break;
        }
        styledSnippet.setSpan(boldSpan, pos, pos + queryLength, 0);
        offset = pos + queryLength;
      }
      snippetView.setText(styledSnippet);
    } else {
      // This may be an error message, so don't try to bold the query terms within it
      snippetView.setText(snippet);
    }
  }
}
 
Example 30
Project: Cable-Android   File: Util.java   Source Code and License 5 votes vote down vote up
public static CharSequence getBoldedString(String value) {
  SpannableString spanned = new SpannableString(value);
  spanned.setSpan(new StyleSpan(Typeface.BOLD), 0,
                  spanned.length(),
                  Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

  return spanned;
}
 
Example 31
Project: instamaterial   File: FeedAdapter.java   Source Code and License 5 votes vote down vote up
private Spannable getStylizedText(String username, String description) {
  Spannable descriptionSpan = new SpannableString(username + " " + description);

  descriptionSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#21425D")), 0,
      username.length(),
      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  descriptionSpan.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
      username.length(),
      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

  return descriptionSpan;
}
 
Example 32
Project: PeSanKita-android   File: MessageRecord.java   Source Code and License 5 votes vote down vote up
protected SpannableString emphasisAdded(String sequence) {
  SpannableString spannable = new SpannableString(sequence);
  spannable.setSpan(new RelativeSizeSpan(0.9f), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  spannable.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

  return spannable;
}
 
Example 33
Project: PeSanKita-android   File: Util.java   Source Code and License 5 votes vote down vote up
public static CharSequence getBoldedString(String value) {
  SpannableString spanned = new SpannableString(value);
  spanned.setSpan(new StyleSpan(Typeface.BOLD), 0,
                  spanned.length(),
                  Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

  return spanned;
}
 
Example 34
Project: markor   File: Highlighter.java   Source Code and License 5 votes vote down vote up
protected void clearSpans(Editable editable) {
    clearCharacterSpanType(editable, TextAppearanceSpan.class);
    clearCharacterSpanType(editable, ForegroundColorSpan.class);
    clearCharacterSpanType(editable, BackgroundColorSpan.class);
    clearCharacterSpanType(editable, StrikethroughSpan.class);
    clearCharacterSpanType(editable, RelativeSizeSpan.class);
    clearCharacterSpanType(editable, StyleSpan.class);
    clearCharacterSpanType(editable, ColorUnderlineSpan.class);
    clearParagraphSpanType(editable, LineBackgroundSpan.class);
    clearParagraphSpanType(editable, LineHeightSpan.class);
}
 
Example 35
Project: Exoplayer2Radio   File: Cea708Decoder.java   Source Code and License 5 votes vote down vote up
public SpannableString buildSpannableString() {
  SpannableStringBuilder spannableStringBuilder =
      new SpannableStringBuilder(captionStringBuilder);
  int length = spannableStringBuilder.length();

  if (length > 0) {
    if (italicsStartPosition != C.POSITION_UNSET) {
      spannableStringBuilder.setSpan(new StyleSpan(Typeface.ITALIC), italicsStartPosition,
          length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    if (underlineStartPosition != C.POSITION_UNSET) {
      spannableStringBuilder.setSpan(new UnderlineSpan(), underlineStartPosition,
          length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    if (foregroundColorStartPosition != C.POSITION_UNSET) {
      spannableStringBuilder.setSpan(new ForegroundColorSpan(foregroundColor),
          foregroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    if (backgroundColorStartPosition != C.POSITION_UNSET) {
      spannableStringBuilder.setSpan(new BackgroundColorSpan(backgroundColor),
          backgroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
  }

  return new SpannableString(spannableStringBuilder);
}
 
Example 36
Project: Exoplayer2Radio   File: WebvttCueParser.java   Source Code and License 5 votes vote down vote up
private static void applySpansForTag(String cueId, StartTag startTag, SpannableStringBuilder text,
    List<WebvttCssStyle> styles, List<StyleMatch> scratchStyleMatches) {
  int start = startTag.position;
  int end = text.length();
  switch(startTag.name) {
    case TAG_BOLD:
      text.setSpan(new StyleSpan(STYLE_BOLD), start, end,
          Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      break;
    case TAG_ITALIC:
      text.setSpan(new StyleSpan(STYLE_ITALIC), start, end,
          Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      break;
    case TAG_UNDERLINE:
      text.setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      break;
    case TAG_CLASS:
    case TAG_LANG:
    case TAG_VOICE:
    case "": // Case of the "whole cue" virtual tag.
      break;
    default:
      return;
  }
  scratchStyleMatches.clear();
  getApplicableStyles(styles, cueId, startTag, scratchStyleMatches);
  int styleMatchesCount = scratchStyleMatches.size();
  for (int i = 0; i < styleMatchesCount; i++) {
    applyStyleToText(text, scratchStyleMatches.get(i).style, start, end);
  }
}
 
Example 37
Project: lex   File: MyListItemView.java   Source Code and License 5 votes vote down vote up
public void bind(BookList item) {
    Lex.say(R.string.name_template)
            .with(LexKey.FIRST_NAME, item.firstName)
            .with(LexKey.LAST_NAME, item.lastName)
            .into(title);

    Lex.list(item.titles)
            .wrappedIn(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC))
            .wrappedIn(new ForegroundColorSpan(Color.WHITE))
            .separator(R.string.comma_separator)
            .twoItemSeparator(R.string.and_separator)
            .lastItemSeparator(R.string.comma_and_separator)
            .into(description);

    Lex.say(R.string.item_count_template)
            .withNumber(LexKey.COUNT, item.titles.length)
            .wrappedIn(new AbsoluteSizeSpan(24, true))
            .wrappedIn(new ForegroundColorSpan(Color.WHITE))
            .withPlural(LexKey.ITEM, item.titles.length, R.plurals.book)
            .wrappedIn(new ForegroundColorSpan(Color.YELLOW))
            .into(bookCount);

    Lex.say(R.string.gpa_template)
            .withNumber(LexKey.NUMBER, item.gpa, GPA_FORMAT)
            .wrappedIn(new AbsoluteSizeSpan(24, true))
            .into(gpa);
}
 
Example 38
Project: SpanEZ   File: SpanEZTest.java   Source Code and License 5 votes vote down vote up
@Test
public void bold_should_add_only_one_span() {
    spanBuilder.style(range, EZ.BOLD)
               .apply();

    verify((SpanEZ) spanBuilder, times(1))
            .addSpan(isA(TargetRange.class), isA(StyleSpan.class));
}
 
Example 39
Project: MyBP   File: Span.java   Source Code and License 5 votes vote down vote up
public static void span(String text, String subText, Switch switchView) {
    SpannableString spanText = new SpannableString(text);
    spanText.setSpan(new ForegroundColorSpan(Color.GRAY), 0, text.length(), 0);
    spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), 0);

    SpannableString spanSubText = new SpannableString(subText);
    spanSubText.setSpan(new RelativeSizeSpan(0.75f), 0, subText.length(), 0);
    spanSubText.setSpan(new ForegroundColorSpan(Color.GRAY), 0, subText.length(), 0);
    switchView.setText("");
    switchView.append(spanText);
    switchView.append("\n");
    switchView.append(spanSubText);
}
 
Example 40
Project: MyBP   File: Span.java   Source Code and License 5 votes vote down vote up
public static void span(String text, String subText, TextView textView) {
    SpannableString spanText = new SpannableString(text);
    spanText.setSpan(new ForegroundColorSpan(Color.GRAY), 0, text.length(), 0);
    spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), 0);

    SpannableString spanSubText = new SpannableString(subText);
    spanSubText.setSpan(new RelativeSizeSpan(0.75f), 0, subText.length(), 0);
    spanSubText.setSpan(new ForegroundColorSpan(Color.GRAY), 0, subText.length(), 0);
    textView.setText("");
    textView.append(spanText);
    textView.append("\n");
    textView.append(spanSubText);
}
 
Example 41
Project: MyBP   File: Span.java   Source Code and License 5 votes vote down vote up
public static void span(String text, Switch switchView) {
    SpannableString spanText = new SpannableString(text);
    spanText.setSpan(new ForegroundColorSpan(Color.GRAY), 0, text.length(), 0);
    spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), 0);

    switchView.setText("");
    switchView.append(spanText);
}
 
Example 42
Project: MyBP   File: Span.java   Source Code and License 5 votes vote down vote up
public static void span(String text, TextView textView) {
    SpannableString spanText = new SpannableString(text);
    spanText.setSpan(new ForegroundColorSpan(Color.GRAY), 0, text.length(), 0);
    spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), 0);

    textView.setText("");
    textView.append(spanText);
}
 
Example 43
Project: CommentView   File: SpanUtil.java   Source Code and License 5 votes vote down vote up
public static Spannable getBoldSpan(String content) {
    if (TextUtils.isEmpty(content)) {
        return null;
    }
    SpannableString spannableString = new SpannableString(content);
    spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, content.length(), Constants.SPAN_FLAGS);
    return spannableString;
}
 
Example 44
Project: Toasty   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private CharSequence getFormattedMessage() {
    final String prefix = "Formatted ";
    final String highlight = "bold italic";
    final String suffix = " text";
    SpannableStringBuilder ssb = new SpannableStringBuilder(prefix).append(highlight).append(suffix);
    int prefixLen = prefix.length();
    ssb.setSpan(new StyleSpan(BOLD_ITALIC),
            prefixLen, prefixLen + highlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ssb;
}
 
Example 45
Project: chromium-for-android-56-debug-video   File: NotificationPlatformBridge.java   Source Code and License 5 votes vote down vote up
/**
 * Creates the ticker text for a notification having |title| and |body|. The notification's
 * title will be printed in bold, followed by the text of the body.
 *
 * @param title Title of the notification.
 * @param body Textual contents of the notification.
 * @return A character sequence containing the ticker's text.
 */
private CharSequence createTickerText(String title, String body) {
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();

    spannableStringBuilder.append(title);
    spannableStringBuilder.append("\n");
    spannableStringBuilder.append(body);

    // Mark the title of the notification as being bold.
    spannableStringBuilder.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
            0, title.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

    return spannableStringBuilder;
}
 
Example 46
Project: chromium-for-android-56-debug-video   File: PaymentRequestSection.java   Source Code and License 5 votes vote down vote up
private CharSequence convertOptionToString(PaymentOption item, boolean useBoldLabel) {
    SpannableStringBuilder builder = new SpannableStringBuilder(item.getLabel());
    if (useBoldLabel) {
        builder.setSpan(
                new StyleSpan(android.graphics.Typeface.BOLD), 0, builder.length(), 0);
    }

    if (!TextUtils.isEmpty(item.getSublabel())) {
        if (builder.length() > 0) builder.append("\n");
        builder.append(item.getSublabel());
    }

    if (!TextUtils.isEmpty(item.getTertiaryLabel())) {
        if (builder.length() > 0) builder.append("\n");
        builder.append(item.getTertiaryLabel());
    }

    if (!item.isComplete() && !TextUtils.isEmpty(item.getEditMessage())) {
        if (builder.length() > 0) builder.append("\n");
        String editMessage = item.getEditMessage();
        builder.append(editMessage);
        Object foregroundSpanner = new ForegroundColorSpan(ApiCompatibilityUtils.getColor(
                getContext().getResources(), R.color.google_blue_700));
        Object sizeSpanner = new AbsoluteSizeSpan(14, true);
        int startIndex = builder.length() - editMessage.length();
        builder.setSpan(foregroundSpanner, startIndex, builder.length(), 0);
        builder.setSpan(sizeSpanner, startIndex, builder.length(), 0);
    }

    return builder;
}
 
Example 47
Project: chromium-for-android-56-debug-video   File: ExpandablePreferenceGroup.java   Source Code and License 5 votes vote down vote up
/**
 * Set the title for the preference group.
 * @param resourceId The resource id of the text to use.
 * @param count The number of entries the preference group contains.
 */
public void setGroupTitle(int resourceId, int count) {
    SpannableStringBuilder spannable =
            new SpannableStringBuilder(getContext().getResources().getString(resourceId));
    String prefCount = String.format(Locale.getDefault(), " - %d", count);
    spannable.append(prefCount);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        spannable.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
                   0,
                   spannable.length() - prefCount.length(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        spannable.setSpan(new TypefaceSpan("sans-serif-medium"),
                   0,
                   spannable.length() - prefCount.length(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    // Color the first part of the title blue.
    ForegroundColorSpan blueSpan = new ForegroundColorSpan(
            ApiCompatibilityUtils.getColor(getContext().getResources(),
                    R.color.pref_accent_color));
    spannable.setSpan(blueSpan, 0, spannable.length() - prefCount.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Gray out the total count of items.
    int gray = ApiCompatibilityUtils.getColor(getContext().getResources(),
            R.color.expandable_group_dark_gray);
    spannable.setSpan(new ForegroundColorSpan(gray),
               spannable.length() - prefCount.length(),
               spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    setTitle(spannable);
}
 
Example 48
Project: chromium-for-android-56-debug-video   File: DuplicateDownloadInfoBar.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to get the text to be displayed on the infobar.
 * @param template Message template.
 * @param fileName Name of the file.
 * @param clickableSpan Action to perform when clicking on the file name.
 * @return message to be displayed on the infobar.
 */
private CharSequence getMessageText(final String template, final String fileName,
        final ClickableSpan clickableSpan) {
    final SpannableString formattedFilePath = new SpannableString(fileName);
    formattedFilePath.setSpan(new StyleSpan(Typeface.BOLD), 0, fileName.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    formattedFilePath.setSpan(clickableSpan, 0, fileName.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return TextUtils.expandTemplate(template, formattedFilePath);
}
 
Example 49
Project: letv   File: StarActivity.java   Source Code and License 5 votes vote down vote up
private void drawStarVoteNum(String num, String unit) {
    if (!TextUtils.isEmpty(num) && !TextUtils.isEmpty(unit)) {
        String str = num + " " + unit;
        int start = num.length();
        int end = str.length();
        SpannableStringBuilder sb = new SpannableStringBuilder(str);
        sb.setSpan(new ForegroundColorSpan(getResources().getColor(2131493270)), start, end, 33);
        sb.setSpan(new StyleSpan(1), 0, start, 33);
        sb.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(2131165477)), start, end, 33);
        this.mStarRankVoteNum.setText(sb);
    }
}
 
Example 50
Project: ANNO1404-Warenrechner-App   File: PopulationNumberDialog.java   Source Code and License 5 votes vote down vote up
private void setAdvancementText(int value, PopulationType.Civilization civilization) {
    String advanceTextStart = getActivity().getString(R.string.advance_to);
    String advanceName = getPopulationTypeByProgress(value, civilization).getString(getContext());
    if (advancementText != null) {
        advancementText.setText(advanceTextStart + " " + advanceName.toLowerCase(), TextView.BufferType.SPANNABLE);

        Spannable sp = (Spannable) advancementText.getText();
        sp.setSpan(new StyleSpan(Typeface.BOLD), advanceTextStart.length(), 1 + advanceTextStart.length() + advanceName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example 51
Project: ZXingAndroidExt   File: SearchBookContentsListItem.java   Source Code and License 5 votes vote down vote up
public void set(SearchBookContentsResult result) {
    pageNumberView.setText(result.getPageNumber());
    String snippet = result.getSnippet();
    if (snippet.isEmpty()) {
        snippetView.setText("");
    } else {
        if (result.getValidSnippet()) {
            String lowerQuery = SearchBookContentsResult.getQuery().toLowerCase(Locale.getDefault());
            String lowerSnippet = snippet.toLowerCase(Locale.getDefault());
            Spannable styledSnippet = new SpannableString(snippet);
            StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
            int queryLength = lowerQuery.length();
            int offset = 0;
            while (true) {
                int pos = lowerSnippet.indexOf(lowerQuery, offset);
                if (pos < 0) {
                    break;
                }
                styledSnippet.setSpan(boldSpan, pos, pos + queryLength, 0);
                offset = pos + queryLength;
            }
            snippetView.setText(styledSnippet);
        } else {
            // This may be an error message, so don't try to bold the query terms within it
            snippetView.setText(snippet);
        }
    }
}
 
Example 52
Project: FCM-toolbox   File: TextPayload.java   Source Code and License 5 votes vote down vote up
@Override
public CharSequence getFormattedCharSequence(Context context) {
    if (display == null) {
        display = new Truss()
                .pushSpan(new StyleSpan(android.graphics.Typeface.BOLD)).append("title: ").popSpan().append(title).append('\n')
                .pushSpan(new StyleSpan(android.graphics.Typeface.BOLD)).append("text: ").popSpan().append(text).append('\n')
                .pushSpan(new StyleSpan(android.graphics.Typeface.BOLD)).append("clipboard: ").popSpan().append(String.valueOf(clipboard))
                .build();
    }
    return display;
}
 
Example 53
Project: SolidRefactor   File: PointOfInterestDetailFragment.java   Source Code and License 5 votes vote down vote up
private SpannableStringBuilder buildBoldLabelString(String label) {
    int x = label.indexOf(':');
    SpannableStringBuilder s = new SpannableStringBuilder(label);
    s.setSpan(new StyleSpan(Typeface.BOLD), 0, x, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return s;
}
 
Example 54
Project: javaide   File: JavaHighlighter.java   Source Code and License 5 votes vote down vote up
private void highlightOther(@NonNull Editable allText,
                                @NonNull CharSequence textToHighlight, int start) {
        //high light number
        for (Matcher m = DECIMAL_NUMBERS.matcher(textToHighlight); m.find(); ) {
            allText.setSpan(new ForegroundColorSpan(codeTheme.getNumberColor()),
                    start + m.start(),
                    start + m.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        for (Matcher m = JAVA_KEYWORDS.matcher(textToHighlight); m.find(); ) {
            allText.setSpan(new ForegroundColorSpan(codeTheme.getKeywordColor()),
                    start + m.start(),
                    start + m.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            allText.setSpan(new StyleSpan(Typeface.BOLD),
                    start + m.start(),
                    start + m.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
//
//        for (Matcher m = SYMBOLS.matcher(textToHighlight); m.find(); ) {
//            allText.setSpan(new ForegroundColorSpan(codeTheme.getOptColor()),
//                    start + m.start(),
//                    start + m.end(),
//                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        }
    }
 
Example 55
Project: Cable-Android   File: MessageRecord.java   Source Code and License 5 votes vote down vote up
protected SpannableString emphasisAdded(String sequence) {
  SpannableString spannable = new SpannableString(sequence);
  spannable.setSpan(new RelativeSizeSpan(0.9f), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  spannable.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

  return spannable;
}
 
Example 56
Project: FCM-toolbox   File: FcmPayloadActivity.java   Source Code and License 5 votes vote down vote up
private static CharSequence buildMessage(@Nullable RemoteMessage message) {
    if (message == null) {
        return null;
    }

    Truss truss = new Truss();
    final Map<String, String> data = message.getData();
    final String messageId = message.getMessageId();
    if (messageId != null) {
        truss.pushSpan(new StyleSpan(Typeface.BOLD)).append("Id: ").popSpan().append(messageId).append('\n');
    }
    final String messageType = message.getMessageType();
    if (messageType != null) {
        truss.pushSpan(new StyleSpan(Typeface.BOLD)).append("Type: ").popSpan().append(messageType).append('\n');
    }
    final String from = message.getFrom();
    if (from != null) {
        truss.pushSpan(new StyleSpan(Typeface.BOLD)).append("From: ").popSpan().append(from).append('\n');
    }
    final String to = message.getTo();
    if (to != null) {
        truss.pushSpan(new StyleSpan(Typeface.BOLD)).append("To: ").popSpan().append(to).append('\n');
    }
    truss.pushSpan(new StyleSpan(Typeface.BOLD)).append("Time: ").popSpan().append(String.valueOf(message.getSentTime())).append('\n');
    truss.pushSpan(new StyleSpan(Typeface.BOLD)).append("Ttl: ").popSpan().append(message.getTtl()).append('\n');

    Set<String> strings = data.keySet();
    for (String key : strings) {
        truss.append('\n');
        String value = data.get(key);
        truss.pushSpan(new StyleSpan(Typeface.BOLD));
        truss.append(key).append(":\n");
        truss.popSpan();
        try {
            final JSONObject json = new JSONObject(value);
            truss.append(json.toString(2));
        } catch (JSONException e) {
            truss.append(value);
        }
    }

    return truss.build();
}
 
Example 57
Project: DailyStudy   File: SpannableStringActivity.java   Source Code and License 5 votes vote down vote up
/**
 * StyleSpan,为文字设置风格(粗体、斜体)
 */
private void style() {
    SpannableString spannableString = new SpannableString("为文字设置粗体、斜体风格");
    StyleSpan styleSpan_B  = new StyleSpan(Typeface.BOLD);
    StyleSpan styleSpan_I  = new StyleSpan(Typeface.ITALIC);
    spannableString.setSpan(styleSpan_B, 5, 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(styleSpan_I, 8, 10, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    bgtext.setHighlightColor(Color.parseColor("#36969696"));
    bgtext.setText(spannableString);
}
 
Example 58
Project: Autocomplete   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void setupMentionsAutocomplete() {
    EditText edit = (EditText) findViewById(R.id.multi);
    float elevation = 6f;
    Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
    AutocompletePolicy policy = new CharPolicy('@'); // Look for @mentions
    AutocompletePresenter<User> presenter = new UserPresenter(this);
    AutocompleteCallback<User> callback = new AutocompleteCallback<User>() {
        @Override
        public boolean onPopupItemClicked(Editable editable, User item) {
            // Replace query text with the full name.
            int[] range = CharPolicy.getQueryRange(editable);
            if (range == null) return false;
            int start = range[0];
            int end = range[1];
            String replacement = item.getUsername();
            editable.replace(start, end, replacement);
            // This is better done with regexes and a TextWatcher, due to what happens when
            // the user clears some parts of the text. Up to you.
            editable.setSpan(new StyleSpan(Typeface.BOLD), start, start+replacement.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return true;
        }
        public void onPopupVisibilityChanged(boolean shown) {}
    };

    mentionsAutocomplete = Autocomplete.<User>on(edit)
            .with(elevation)
            .with(backgroundDrawable)
            .with(policy)
            .with(presenter)
            .with(callback)
            .build();
}
 
Example 59
Project: Autocomplete   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void setupMaleFemaleAutocomplete() {
    EditText edit = (EditText) findViewById(R.id.topbar);
    float elevation = 6f;
    Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
    AutocompletePresenter<User> presenter = new MaleFemalePresenter(this);
    AutocompleteCallback<User> callback = new AutocompleteCallback<User>() {
        @Override
        public boolean onPopupItemClicked(Editable editable, User item) {
            editable.clear();
            editable.append(item.getFullname())
                    .append(" ")
                    .append(item.isFemale() ? "(Female)" : "(Male)");
            editable.setSpan(new StyleSpan(Typeface.BOLD), 0, item.getFullname().length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return true;
        }

        public void onPopupVisibilityChanged(boolean shown) {}
    };

    maleFemaleAutocomplete = Autocomplete.<User>on(edit)
            .with(elevation)
            .with(backgroundDrawable)
            .with(presenter)
            .with(callback)
            .build();
}
 
Example 60
Project: revolution-irc   File: TextFormatBar.java   Source Code and License 5 votes vote down vote up
public void updateFormattingAtCursor() {
    if (mEditText == null)
        return;
    Editable text = mEditText.getText();
    int start = mEditText.getSelectionStart();
    int end = mEditText.getSelectionEnd();
    Object[] spans = text.getSpans(start, end, Object.class);

    mBoldButton.setSelected(false);
    mItalicButton.setSelected(false);
    mUnderlineButton.setSelected(false);

    int fgColor = -1;
    int bgColor = -1;

    for (Object span : spans) {
        if (!SpannableStringHelper.checkSpanInclude(text, span, start, end) ||
                (text.getSpanFlags(span) & Spanned.SPAN_COMPOSING) != 0)
            continue;
        if (span instanceof StyleSpan) {
            int style = ((StyleSpan) span).getStyle();
            if (style == Typeface.BOLD)
                mBoldButton.setSelected(true);
            else if (style == Typeface.ITALIC)
                mItalicButton.setSelected(true);
        } else if (span instanceof UnderlineSpan) {
            mUnderlineButton.setSelected(true);
        } else if (span instanceof ForegroundColorSpan) {
            fgColor = ((ForegroundColorSpan) span).getForegroundColor();
        } else if (span instanceof BackgroundColorSpan) {
            bgColor = ((BackgroundColorSpan) span).getBackgroundColor();
        }
    }

    ImageViewCompat.setImageTintList(mTextColorValue, fgColor != -1
            ? ColorStateList.valueOf(fgColor) : mTextColorValueDefault);
    ImageViewCompat.setImageTintList(mFillColorValue, bgColor != -1
            ? ColorStateList.valueOf(bgColor) : mFillColorValueDefault);
}