Java Code Examples for android.text.style.StyleSpan

The following examples show how to use android.text.style.StyleSpan. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: android-utils   Source File: Utils.java    License: MIT License 6 votes vote down vote up
/**
 * Typefaces the string as bold.
 * If sub-string is null, entire string will be typefaced as bold and returned.
 *
 * @param string
 * @param subString The subString within the string to bold. Pass null to bold entire string.
 * @return {@link android.text.SpannableString}
 */
public static SpannableStringBuilder toBold(String string, String subString) {
    if (TextUtils.isEmpty(string)) {
        return new SpannableStringBuilder("");
    }

    SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(string);

    StyleSpan bss = new StyleSpan(Typeface.BOLD);
    if (subString != null) {
        int substringNameStart = string.toLowerCase().indexOf(subString);
        if (substringNameStart > -1) {
            spannableBuilder.setSpan(bss, substringNameStart, substringNameStart + subString.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    } else {
        // set entire text to bold
        spannableBuilder.setSpan(bss, 0, spannableBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }
    return spannableBuilder;
}
 
Example 2
Source Project: Dashchan   Source File: PostItem.java    License: Apache License 2.0 6 votes vote down vote up
public CharSequence getComment(String repliesToPost) {
	SpannableString comment = new SpannableString(getComment());
	LinkSpan[] spans = comment.getSpans(0, comment.length(), LinkSpan.class);
	if (spans != null) {
		String commentString = comment.toString();
		repliesToPost = ">>" + repliesToPost;
		for (LinkSpan linkSpan : spans) {
			int start = comment.getSpanStart(linkSpan);
			if (commentString.indexOf(repliesToPost, start) == start) {
				int end = comment.getSpanEnd(linkSpan);
				comment.setSpan(new StyleSpan(Typeface.BOLD), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
		}
	}
	return comment;
}
 
Example 3
Source Project: talkback   Source File: SearchScreenOverlay.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Makes all instances of {@code keyword} within {@code fullString} bold.
 *
 * @param matchedInfo the matchedNodeInfo containing the matched {@code AccessibilityNode} and
 *     {@code MatchResult}
 * @return the fullString with all contained keyword set as bold or null if node is not available
 */
static SpannableStringBuilder makeAllKeywordBold(@Nullable MatchedNodeInfo matchedInfo) {
  if (matchedInfo == null || TextUtils.isEmpty(matchedInfo.getNodeText())) {
    return null;
  }

  SpannableStringBuilder updatedString = new SpannableStringBuilder(matchedInfo.getNodeText());
  if (!matchedInfo.hasMatchedResult()) {
    return updatedString;
  }

  // Clear existing formatting spans since we only want the highlight span shown in the result
  // list.
  clearFormattingSpans(updatedString);

  for (MatchResult match : matchedInfo.matchResults()) {
    updatedString.setSpan(
        new StyleSpan(Typeface.BOLD),
        match.start(),
        match.end(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  }

  return updatedString;
}
 
Example 4
Source Project: Conversations   Source File: MessageAdapter.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void toggleWhisperInfo(ViewHolder viewHolder, final Message message, final boolean darkBackground) {
    if (message.isPrivateMessage()) {
        final String privateMarker;
        if (message.getStatus() <= Message.STATUS_RECEIVED) {
            privateMarker = activity.getString(R.string.private_message);
        } else {
            Jid cp = message.getCounterpart();
            privateMarker = activity.getString(R.string.private_message_to, Strings.nullToEmpty(cp == null ? null : cp.getResource()));
        }
        final SpannableString body = new SpannableString(privateMarker);
        body.setSpan(new ForegroundColorSpan(getMessageTextColor(darkBackground, false)), 0, privateMarker.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        body.setSpan(new StyleSpan(Typeface.BOLD), 0, privateMarker.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        viewHolder.messageBody.setText(body);
        viewHolder.messageBody.setVisibility(View.VISIBLE);
    } else {
        viewHolder.messageBody.setVisibility(View.GONE);
    }
}
 
Example 5
Source Project: FirebaseUI-Android   Source File: TextHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static void boldAllOccurencesOfText(@NonNull SpannableStringBuilder builder,
                                           @NonNull String text,
                                           @NonNull String textToBold) {
    int fromIndex = 0;
    while (fromIndex < text.length()) {
        int start = text.indexOf(textToBold, fromIndex);
        int end = start + textToBold.length();
        if (start == -1 || end >= text.length()) {
            break;
        }
        builder.setSpan(new StyleSpan(Typeface.BOLD),
                start,
                end,
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        fromIndex = end + 1;
    }
}
 
Example 6
Source Project: talk-android   Source File: MessageFormatter.java    License: MIT License 6 votes vote down vote up
public static Spannable formatHighlightSpan(String html, Resources res) {
    HighlightSpan highlightSpan;
    if (Html.fromHtml(html) instanceof SpannableStringBuilder) {
        SpannableStringBuilder value = (SpannableStringBuilder) Html.fromHtml(html);
        StyleSpan[] spans = value.getSpans(0, html.length(), StyleSpan.class);
        for (StyleSpan span : spans) {
            int start = value.getSpanStart(span);
            int end = value.getSpanEnd(span);
            value.removeSpan(span);
            highlightSpan = new HighlightSpan(res);
            value.setSpan(highlightSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return value;
    } else {
        return new SpannableStringBuilder(html);
    }
}
 
Example 7
Source Project: MHViewer   Source File: Html.java    License: Apache License 2.0 6 votes vote down vote up
private static void endHeader(SpannableStringBuilder text) {
    int len = text.length();
    Object obj = getLast(text, Header.class);

    int where = text.getSpanStart(obj);

    text.removeSpan(obj);

    // Back off not to change only the text, not the blank line.
    while (len > where && text.charAt(len - 1) == '\n') {
        len--;
    }

    if (where != len) {
        Header h = (Header) obj;

        text.setSpan(new RelativeSizeSpan(HEADER_SIZES[h.mLevel]),
                where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.setSpan(new StyleSpan(Typeface.BOLD),
                where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example 8
public SpannableStringBuilder getDescription(Context context) {
    SpannableStringBuilder builder = new SpannableStringBuilder();

    // TODO XXX: i18n (w/ proper pluralisation)

    MiscUtils.appendAndSetSpan(builder, "Block(s): ",
            new StyleSpan(android.graphics.Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(MiscUtils.unparseIntRanges(blockNumbers));
    builder.append('\n');

    MiscUtils.appendAndSetSpan(builder, "Key: ",
            new StyleSpan(android.graphics.Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(key.toString());
    builder.append('\n');

    MiscUtils.appendAndSetSpan(builder, "Slot(s): ",
            new StyleSpan(android.graphics.Typeface.BOLD), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(
            keySlotAttempts == KeySlotAttempts.BOTH ? context.getString(R.string.both) :
            keySlotAttempts.toString());

    return builder;
}
 
Example 9
Source Project: Knife   Source File: KnifeText.java    License: Apache License 2.0 6 votes vote down vote up
protected void styleValid(int style, int start, int end) {
    switch (style) {
        case Typeface.NORMAL:
        case Typeface.BOLD:
        case Typeface.ITALIC:
        case Typeface.BOLD_ITALIC:
            break;
        default:
            return;
    }

    if (start >= end) {
        return;
    }

    getEditableText().setSpan(new StyleSpan(style), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
 
Example 10
Source Project: 1Rramp-Android   Source File: CompetitionDetailsHeaderView.java    License: MIT License 6 votes vote down vote up
private void setParticipationHashtagInfo(String hashtag) {
  hashtag = "#" + hashtag;
  String part1 = "Participate using ";
  String part3 = " from any other steem platform.";
  int hashtagLen = hashtag.length();
  int part1Len = part1.length();

  int spanStart = part1Len;
  int spanEnd = part1Len + hashtagLen;
  Spannable wordtoSpan = new SpannableString(part1 + hashtag + part3);
  wordtoSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#3F72AF")),
    spanStart,
    spanEnd,
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  StyleSpan bss = new StyleSpan(Typeface.BOLD);
  wordtoSpan.setSpan(bss,
    spanStart,
    spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  participationHashtagText.setText(wordtoSpan);
}
 
Example 11
private void setupInfo(PostItem item) {
    String subreddit = "/r/"+item.getSubreddit();
    CustomClickable subredditClickable = new CustomClickable(this, true);

    StringUtils.SpannableBuilder builder = StringUtils.newSpannableBuilder(getContext())
            .setTextView(headerTimeSubredditView)
            .append("submitted " + item.getTime() + " hrs ago to ")
            .append(subreddit, subredditClickable, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            .span(new ForegroundColorSpan(Color.rgb(204, 0, 0)), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            .append(" by ");

    if(item.distinguished() != null){
        final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
        builder.append(item.getAuthor(), new CustomClickable(this, false), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                .span(new ForegroundColorSpan(getAuthorBackgroundColor(item)), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                .span(bss, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }else{
        builder.append(item.getAuthor(), new CustomClickable(this, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                .span(new ForegroundColorSpan(Color.rgb(204, 0, 0)), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    builder.clickable().buildSpannable();
}
 
Example 12
Source Project: mcumgr-android   Source File: FilesDownloadFragment.java    License: Apache License 2.0 6 votes vote down vote up
private void printError(@Nullable final String error) {
    mDivider.setVisibility(View.VISIBLE);
    mResult.setVisibility(View.VISIBLE);

    if (error != null) {
        final SpannableString spannable = new SpannableString(error);
        spannable.setSpan(new ForegroundColorSpan(
                        ContextCompat.getColor(requireContext(), R.color.colorError)),
                0, error.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannable.setSpan(new StyleSpan(Typeface.BOLD),
                0, error.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mResult.setText(spannable);
    } else {
        mResult.setText(null);
    }
}
 
Example 13
Source Project: Gander   Source File: FormatUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static CharSequence formatFormEncoded(String formEncoded) {
    try {
        Truss truss = new Truss();
        if (formEncoded != null) {
            formEncoded = URLDecoder.decode(formEncoded, "UTF-8");
            String[] pairs = formEncoded.split("&");
            for (String pair : pairs) {
                if (pair.contains("=")) {
                    int idx = pair.indexOf("=");

                    truss.pushSpan(new StyleSpan(android.graphics.Typeface.BOLD));
                    truss.append(pair.substring(0, idx)).append("= ");
                    truss.popSpan();
                    truss.append(pair.substring(idx + 1)).append("\n");
                }
            }
        }
        return truss.build();
    } catch (Exception e) {
        Logger.e("non form url content content", e);
        return formEncoded;
    }
}
 
Example 14
Source Project: AndFChat   Source File: ChatEntry.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Spannable getChatMessage(Context context) {
    if (spannedText == null) {
        Spannable dateSpan = createDateSpannable(context);
        Spannable textSpan = createText(context);

        // Time
        SpannableStringBuilder finishedText = new SpannableStringBuilder(dateSpan);
        // Delimiter
        finishedText.append(delimiterBetweenDateAndName);
        // Name
        finishedText.append(new NameSpannable(owner, getNameColorId(), context.getResources()));
        // Delimiter
        finishedText.append(delimiterBetweenNameAndText);
        // Message
        finishedText.append(textSpan);

        // Add overall styles
        if (getTypeFace() != null) {
            finishedText.setSpan(new StyleSpan(getTypeFace()), DATE_CHAR_LENGTH, finishedText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }

        spannedText = finishedText;
    }
    return spannedText;
}
 
Example 15
Source Project: Overchan-Android   Source File: HtmlParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
public HtmlToSpannedConverter(String subject, String source, ThemeColors colors, HtmlParser.ImageGetter imageGetter, boolean openSpoilers,
        Parser parser) {
    mSource = source;
    mSpannableStringBuilder = new SpannableStringBuilder();
    if (!TextUtils.isEmpty(subject)) {
        mSpannableStringBuilder.append(subject);
        int len = mSpannableStringBuilder.length();
        mSpannableStringBuilder.setSpan(new RelativeSizeSpan(1.25f), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mSpannableStringBuilder.setSpan(new StyleSpan(Typeface.BOLD), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (colors != null) {
            mSpannableStringBuilder.setSpan(new ForegroundColorSpan(colors.subjectForeground), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        mSpannableStringBuilder.append('\n');
        mStartLength = mSpannableStringBuilder.length();
    }
    mColors = colors;
    mOpenSpoilers = openSpoilers;
    mImageGetter = imageGetter;
    mReader = parser;
}
 
Example 16
Source Project: Telegram-FOSS   Source File: Cea708Decoder.java    License: GNU General Public License v2.0 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 17
Source Project: mollyim-android   Source File: Util.java    License: GNU General Public License v3.0 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 18
Source Project: xDrip   Source File: BasalProfileEditor.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void refreshTotals() {

        final float current = BasalChart.getTotalBasal(chart.getColumnChartData());
        final float previous = BasalChart.getTotalImmutableBasal(chart.getColumnChartData());
        final float difference = current - previous;

        String result = "";
        if (current == previous) {
            result = String.format("Daily basal: ^%s^ U", JoH.qs0(current, 2));
        } else {
            String differenceText = (difference > 0 ? "+" : "") + JoH.qs0(difference, 2);
            result = String.format("Daily basal: ^%s^ U, was: %s, change: ^%s^", JoH.qs0(current, 2), JoH.qs0(previous, 2), differenceText);
        }

        // TODO extract this to span class
        final List<Integer> positions = new ArrayList<>();
        int matchpos = -1;
        while ((matchpos = result.indexOf('^', matchpos + 1)) > -1) {
            positions.add(matchpos - positions.size());
        }
        final SpannableStringBuilder span = new SpannableStringBuilder(result.replaceAll("\\^", ""));

        for (matchpos = 0; matchpos < positions.size() - 1; matchpos += 2) {
            final StyleSpan style = new StyleSpan(android.graphics.Typeface.BOLD);
            span.setSpan(style, positions.get(matchpos), positions.get(matchpos + 1), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }


        try {
            getSupportActionBar().setSubtitle(R.string.basal_editor);
            getSupportActionBar().setTitle(span);
            fixElipsus(null); // how often do we actually need to do this??
            //get
        } catch (Exception e) {
            android.util.Log.e(TAG, "Got exception: " + e);
        }
    }
 
Example 19
Source Project: K-Sonic   Source File: Cea708Decoder.java    License: MIT 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 20
Source Project: Slide   Source File: SortingUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static Spannable[] getSortingTimesSpannables(int sortingId, String sub) {
    ArrayList<Spannable> spannables = new ArrayList<>();
    String[] sortingStrings = getSortingTimesStrings();
    for (int i = 0; i < sortingStrings.length; i++) {
        SpannableString spanString = new SpannableString(sortingStrings[i]);
        if (i == sortingId) {
            spanString.setSpan(new ForegroundColorSpan(
                            new ColorPreferences(Reddit.getAppContext()).getColor(sub)), 0,
                    spanString.length(), 0);
            spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
        }
        spannables.add(spanString);
    }
    return spannables.toArray(new Spannable[spannables.size()]);
}
 
Example 21
Source Project: SpanEZ   Source File: SpanEZTest.java    License: Apache License 2.0 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 22
Source Project: deltachat-android   Source File: Util.java    License: GNU General Public License v3.0 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 23
Source Project: auid2   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final SpannableStringBuilder ssb = new SpannableStringBuilder();
    final int flag = Spannable.SPAN_EXCLUSIVE_EXCLUSIVE;
    int start;
    int end;

    // Regular text
    ssb.append("This text is normal, but ");

    // Bold text
    start = ssb.length();
    ssb.append("this text is bold");
    end = ssb.length();
    ssb.setSpan(new StyleSpan(Typeface.BOLD), start, end, flag);

    // Inline image
    ssb.append('\n');
    start = end + 1;
    ssb.append('\uFFFC'); // Unicode replacement character
    end = ssb.length();
    ssb.setSpan(new ImageSpan(this, R.mipmap.ic_launcher), start, end, flag);

    // Stretched text
    start = end;
    ssb.append("This text is wide");
    end = ssb.length();
    ssb.setSpan(new ScaleXSpan(2f), start, end, flag);

    // Assign to TextView
    final TextView tv = (TextView) findViewById(R.id.textView);
    tv.setText(ssb);
}
 
Example 24
Source Project: Conversations   Source File: StylingHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static ParcelableSpan clone(ParcelableSpan span) {
	if (span instanceof ForegroundColorSpan) {
		return new ForegroundColorSpan(((ForegroundColorSpan) span).getForegroundColor());
	} else if (span instanceof TypefaceSpan) {
		return new TypefaceSpan(((TypefaceSpan) span).getFamily());
	} else if (span instanceof StyleSpan) {
		return new StyleSpan(((StyleSpan) span).getStyle());
	} else if (span instanceof StrikethroughSpan) {
		return new StrikethroughSpan();
	} else {
		throw new AssertionError("Unknown Span");
	}
}
 
Example 25
Source Project: writeily-pro   Source File: Highlighter.java    License: MIT License 5 votes vote down vote up
private void clearSpans(Editable e) {

        clearSpanType(e, TextAppearanceSpan.class);
        clearSpanType(e, ForegroundColorSpan.class);
        clearSpanType(e, BackgroundColorSpan.class);
        clearSpanType(e, StrikethroughSpan.class);
        clearSpanType(e, StyleSpan.class);
    }
 
Example 26
Source Project: homeassist   Source File: LogbookActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onBindViewHolder(final LogbookViewHolder viewHolder, final int position) {
    final LogSheet logSheet = items.get(position);
    Log.d("YouQi", "rendering: " + position + "logSheet.message: " + logSheet.message);
    //viewHolder.mNameView.setText(logSheet.name);
    viewHolder.mStateText.setText(TextUtils.concat(dateFormat.format(logSheet.when.getTime()), "\n", CommonUtil.getSpanText(LogbookActivity.this, DateUtils.getRelativeTimeSpanString(logSheet.when.getTime()).toString(), null, 0.9f)));
    viewHolder.mIconView.setText(MDIFont.getIcon("mdi:information-outline"));

    Entity entity = getEntity(logSheet.entityId);
    if (entity != null) {
        viewHolder.mIconView.setText(entity.getMdiIcon());
    }


    Spannable wordtoSpan1 = new SpannableString(logSheet.name);
    wordtoSpan1.setSpan(new RelativeSizeSpan(1.0f), 0, wordtoSpan1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    wordtoSpan1.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, wordtoSpan1.length(), 0);

    Spannable wordtoSpan2 = new SpannableString(logSheet.message);
    wordtoSpan2.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.md_grey_500, null)), 0, wordtoSpan2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    wordtoSpan2.setSpan(new RelativeSizeSpan(0.95f), 0, wordtoSpan2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    //viewHolder.mNameView.setText(TextUtils.concat(wordtoSpan1, " ", wordtoSpan2));
    viewHolder.mNameView.setText(logSheet.name);
    viewHolder.mSubText.setText(logSheet.message);

}
 
Example 27
Source Project: revolution-irc   Source File: TextFormatBar.java    License: GNU General Public License v3.0 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);
}
 
Example 28
Source Project: Knife   Source File: KnifeText.java    License: Apache License 2.0 5 votes vote down vote up
protected void styleInvalid(int style, int start, int end) {
    switch (style) {
        case Typeface.NORMAL:
        case Typeface.BOLD:
        case Typeface.ITALIC:
        case Typeface.BOLD_ITALIC:
            break;
        default:
            return;
    }

    if (start >= end) {
        return;
    }

    StyleSpan[] spans = getEditableText().getSpans(start, end, StyleSpan.class);
    List<KnifePart> list = new ArrayList<>();

    for (StyleSpan span : spans) {
        if (span.getStyle() == style) {
            list.add(new KnifePart(getEditableText().getSpanStart(span), getEditableText().getSpanEnd(span)));
            getEditableText().removeSpan(span);
        }
    }

    for (KnifePart part : list) {
        if (part.isValid()) {
            if (part.getStart() < start) {
                styleValid(style, part.getStart(), start);
            }

            if (part.getEnd() > end) {
                styleValid(style, end, part.getEnd());
            }
        }
    }
}
 
Example 29
/**
 * 对用户名进行加粗并进行组装内容
 * @param accountName
 * @return
 */
private SpannableStringBuilder setAccountName(String accountName){
    SpannableStringBuilder spannableString = new SpannableStringBuilder(accountName);
    //设置字体粗细
    StyleSpan span = new StyleSpan(Typeface.BOLD);
    spannableString.setSpan(span,
            0,
            spannableString.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannableString;
}
 
Example 30
Source Project: edx-app-android   Source File: DiscussionTextUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void setAuthorText(@NonNull TextView textView, @NonNull IAuthorData authorData) {
    final CharSequence authorText;
    {
        final Context context = textView.getContext();
        List<CharSequence> joinableStrings = new ArrayList<>();
        final String author = authorData.getAuthor();
        if (!TextUtils.isEmpty(author)) {
            final SpannableString authorSpan = new SpannableString(author);
            // Change the author text color and style
            if (!authorData.isAuthorAnonymous()) {
                authorSpan.setSpan(new ForegroundColorSpan(context.getResources().
                                getColor(R.color.edx_brand_primary_base)), 0,
                        authorSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            authorSpan.setSpan(new StyleSpan(Typeface.BOLD), 0, authorSpan.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            joinableStrings.add(authorSpan);
        }

        final String authorLabel = authorData.getAuthorLabel();
        if (!TextUtils.isEmpty(authorLabel)) {
            joinableStrings.add(ResourceUtil.getFormattedString(context.getResources(),
                    R.string.discussion_post_author_label_attribution, "text", authorLabel));
        }

        authorText = org.edx.mobile.util.TextUtils.join(" ", joinableStrings);
    }
    if (TextUtils.isEmpty(authorText)) {
        textView.setVisibility(View.GONE);
    } else {
        textView.setText(authorText);
    }
}