Example usage for android.text.style StyleSpan StyleSpan

List of usage examples for android.text.style StyleSpan StyleSpan

Introduction

In this page you can find the example usage for android.text.style StyleSpan StyleSpan.

Prototype

public StyleSpan(@NonNull Parcel src) 

Source Link

Document

Creates a StyleSpan from a parcel.

Usage

From source file:org.chromium.chrome.browser.omnibox.SuggestionView.java

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;
            }/*ww w. j a va2 s  .com*/
            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;
}

From source file:org.mariotaku.twidere.view.holder.ActivityTitleSummaryViewHolder.java

private Spanned getTitleStringByFriends(int stringRes, int stringResMulti, ParcelableUser[] sources,
        Object[] targets) {/*from   ww w  .j a  v a 2s. c  om*/
    if (sources == null || sources.length == 0)
        return null;
    final Context context = adapter.getContext();
    final Resources resources = context.getResources();
    final Configuration configuration = resources.getConfiguration();
    final UserColorNameManager manager = adapter.getUserColorNameManager();
    final boolean nameFirst = adapter.isNameFirst();
    final SpannableString firstSourceName = new SpannableString(
            manager.getDisplayName(sources[0], nameFirst, false));
    firstSourceName.setSpan(new StyleSpan(Typeface.BOLD), 0, firstSourceName.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    final String displayName;
    final Object target = targets[0];
    if (target instanceof ParcelableUser) {
        displayName = manager.getDisplayName((ParcelableUser) target, nameFirst, false);
    } else if (target instanceof ParcelableStatus) {
        displayName = manager.getDisplayName((ParcelableStatus) target, nameFirst, false);
    } else {
        throw new IllegalArgumentException();
    }
    final SpannableString firstTargetName = new SpannableString(displayName);
    firstTargetName.setSpan(new StyleSpan(Typeface.BOLD), 0, firstTargetName.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    if (sources.length == 1) {
        final String format = context.getString(stringRes);
        return SpanFormatter.format(configuration.locale, format, firstSourceName, firstTargetName);
    } else if (sources.length == 2) {
        final String format = context.getString(stringResMulti);
        final SpannableString secondSourceName = new SpannableString(
                manager.getDisplayName(sources[1], nameFirst, false));
        secondSourceName.setSpan(new StyleSpan(Typeface.BOLD), 0, secondSourceName.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return SpanFormatter.format(configuration.locale, format, firstSourceName, secondSourceName,
                firstTargetName);
    } else {
        final int othersCount = sources.length - 1;
        final SpannableString nOthers = new SpannableString(
                resources.getQuantityString(R.plurals.N_others, othersCount, othersCount));
        nOthers.setSpan(new StyleSpan(Typeface.BOLD), 0, nOthers.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        final String format = context.getString(stringResMulti);
        return SpanFormatter.format(configuration.locale, format, firstSourceName, nOthers, firstTargetName);
    }
}

From source file:org.sufficientlysecure.keychain.ui.ViewKeyKeybaseFragment.java

@Override
public void onCryptoOperationError(KeybaseVerificationResult result) {

    result.createNotify(getActivity()).show();

    SpannableStringBuilder ssb = new SpannableStringBuilder();

    ssb.append(getString(R.string.keybase_proof_failure));
    String msg = getString(result.getLog().getLast().mType.mMsgId);
    if (msg == null) {
        msg = getString(R.string.keybase_unknown_proof_failure);
    }//w w w  .  j  a  va  2 s  . co  m
    StyleSpan bold = new StyleSpan(Typeface.BOLD);
    ssb.setSpan(bold, 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.append("\n\n").append(msg);

    displaySpannableResult(ssb);
}

From source file:com.nttec.everychan.ui.presentation.HtmlParser.java

private void handleEndTag(String tag) {
    if (tag.equalsIgnoreCase("br")) {
        handleBr(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("p")) {
        handleP(mSpannableStringBuilder, mStartLength, mLastPTagLength);
    } else if (tag.equalsIgnoreCase("div")) {
        handleP(mSpannableStringBuilder, mStartLength, mLastPTagLength);
    } else if (tag.equalsIgnoreCase("strong")) {
        end(mSpannableStringBuilder, Bold.class, new StyleSpan(Typeface.BOLD));
    } else if (tag.equalsIgnoreCase("b")) {
        end(mSpannableStringBuilder, Bold.class, new StyleSpan(Typeface.BOLD));
    } else if (tag.equalsIgnoreCase("em")) {
        end(mSpannableStringBuilder, Italic.class, new StyleSpan(Typeface.ITALIC));
    } else if (tag.equalsIgnoreCase("cite")) {
        end(mSpannableStringBuilder, Italic.class, new StyleSpan(Typeface.ITALIC));
    } else if (tag.equalsIgnoreCase("dfn")) {
        end(mSpannableStringBuilder, Italic.class, new StyleSpan(Typeface.ITALIC));
    } else if (tag.equalsIgnoreCase("i")) {
        end(mSpannableStringBuilder, Italic.class, new StyleSpan(Typeface.ITALIC));
    } else if (tag.equalsIgnoreCase("s")) {
        end(mSpannableStringBuilder, Strike.class, new StrikethroughSpan());
    } else if (tag.equalsIgnoreCase("strike")) {
        end(mSpannableStringBuilder, Strike.class, new StrikethroughSpan());
    } else if (tag.equalsIgnoreCase("del")) {
        end(mSpannableStringBuilder, Strike.class, new StrikethroughSpan());
    } else if (tag.equalsIgnoreCase("big")) {
        end(mSpannableStringBuilder, Big.class, new RelativeSizeSpan(1.25f));
    } else if (tag.equalsIgnoreCase("small")) {
        end(mSpannableStringBuilder, Small.class, new RelativeSizeSpan(0.8f));
    } else if (tag.equalsIgnoreCase("font")) {
        endFont(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("blockquote")) {
        handleP(mSpannableStringBuilder, mStartLength, mLastPTagLength);
        endBlockquote(mSpannableStringBuilder, mColors);
    } else if (tag.equalsIgnoreCase("tt")) {
        end(mSpannableStringBuilder, Monospace.class, new TypefaceSpan("monospace"));
    } else if (tag.equalsIgnoreCase("code")) {
        end(mSpannableStringBuilder, Monospace.class, new TypefaceSpan("monospace"));
    } else if (tag.equalsIgnoreCase("ul")) {
        if (!mListTags.isEmpty())
            mListTags.removeFirst();// w  w w.ja va  2 s  .co  m
    } else if (tag.equalsIgnoreCase("ol")) {
        if (!mListTags.isEmpty())
            mListTags.removeFirst();
    } else if (tag.equalsIgnoreCase("li")) {
        //??  ?? <li>
    } else if (tag.equalsIgnoreCase("tr")) {
        handleTr(mSpannableStringBuilder, false);
    } else if (tag.equalsIgnoreCase("td")) {
        handleTd(mSpannableStringBuilder, false);
    } else if (tag.equalsIgnoreCase("a")) {
        endA(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("u")) {
        end(mSpannableStringBuilder, Underline.class, new UnderlineSpan());
    } else if (tag.equalsIgnoreCase("sup")) {
        end(mSpannableStringBuilder, Super.class, new SuperscriptSpan());
    } else if (tag.equalsIgnoreCase("sub")) {
        end(mSpannableStringBuilder, Sub.class, new SubscriptSpan());
    } else if (tag.length() == 2 && Character.toLowerCase(tag.charAt(0)) == 'h' && tag.charAt(1) >= '1'
            && tag.charAt(1) <= '6') {
        handleP(mSpannableStringBuilder, mStartLength, mLastPTagLength);
        endHeader(mSpannableStringBuilder);
    } else if (tag.equalsIgnoreCase("span")) {
        endSpan(mSpannableStringBuilder, mColors, mOpenSpoilers);
    } else if (tag.equalsIgnoreCase("aibquote")) {
        end(mSpannableStringBuilder, Aibquote.class,
                new ForegroundColorSpan(mColors != null ? mColors.quoteForeground : Color.GREEN));
    } else if (tag.equalsIgnoreCase("aibspoiler")) {
        endAibspoiler(mSpannableStringBuilder, mColors, mOpenSpoilers);
    } /* else if (mTagHandler != null) {
      mTagHandler.handleTag(false, tag, mSpannableStringBuilder, mReader);
      }*/
}

From source file:org.chromium.chrome.browser.notifications.NotificationUIManager.java

/**
 * 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.
 *///from   w ww. j  a va  2 s.  co  m
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;
}

From source file:net.maa123.tatuky.MainActivity.java

private void setupSearchView() {
    searchView.attachNavigationDrawerToMenuButton(drawer.getDrawerLayout());

    // Setup content descriptions for the different elements in the search view.
    final View leftAction = searchView.findViewById(R.id.left_action);
    leftAction.setContentDescription(getString(R.string.action_open_drawer));
    searchView.setOnFocusChangeListener(new FloatingSearchView.OnFocusChangeListener() {
        @Override/*from w  w  w  .ja  v  a2 s  . c  o m*/
        public void onFocus() {
            leftAction.setContentDescription(getString(R.string.action_close));
        }

        @Override
        public void onFocusCleared() {
            leftAction.setContentDescription(getString(R.string.action_open_drawer));
        }
    });
    View clearButton = searchView.findViewById(R.id.clear_btn);
    clearButton.setContentDescription(getString(R.string.action_clear));

    searchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
        @Override
        public void onSearchTextChanged(String oldQuery, String newQuery) {
            if (!oldQuery.equals("") && newQuery.equals("")) {
                searchView.clearSuggestions();
                return;
            }

            if (newQuery.length() < 3) {
                return;
            }

            searchView.showProgress();

            mastodonAPI.searchAccounts(newQuery, false, 5).enqueue(new Callback<List<Account>>() {
                @Override
                public void onResponse(Call<List<Account>> call, Response<List<Account>> response) {
                    if (response.isSuccessful()) {
                        searchView.swapSuggestions(response.body());
                        searchView.hideProgress();
                    } else {
                        searchView.hideProgress();
                    }
                }

                @Override
                public void onFailure(Call<List<Account>> call, Throwable t) {
                    searchView.hideProgress();
                }
            });
        }
    });

    searchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
        @Override
        public void onSuggestionClicked(SearchSuggestion searchSuggestion) {
            Account accountSuggestion = (Account) searchSuggestion;
            Intent intent = new Intent(MainActivity.this, AccountActivity.class);
            intent.putExtra("id", accountSuggestion.id);
            startActivity(intent);
        }

        @Override
        public void onSearchAction(String currentQuery) {
        }
    });

    searchView.setOnBindSuggestionCallback(new SearchSuggestionsAdapter.OnBindSuggestionCallback() {
        @Override
        public void onBindSuggestion(View suggestionView, ImageView leftIcon, TextView textView,
                SearchSuggestion item, int itemPosition) {
            Account accountSuggestion = ((Account) item);

            Picasso.with(MainActivity.this).load(accountSuggestion.avatar)
                    .placeholder(R.drawable.avatar_default).into(leftIcon);

            String searchStr = accountSuggestion.getDisplayName() + " " + accountSuggestion.username;
            final SpannableStringBuilder str = new SpannableStringBuilder(searchStr);

            str.setSpan(new StyleSpan(Typeface.BOLD), 0, accountSuggestion.getDisplayName().length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(str);
            textView.setMaxLines(1);
            textView.setEllipsize(TextUtils.TruncateAt.END);
        }
    });
}

From source file:com.android.deskclock.Utils.java

/**
 * @param context - context used to get time format string resource
 * @param showAmPm - include the am/pm string if true
 * @return format string for 12 hours mode time
 *///from www  .  j  av  a2  s  .c o  m
public static CharSequence get12ModeFormat(Context context, boolean showAmPm) {
    String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "hma");
    if (!showAmPm) {
        pattern = pattern.replaceAll("a", "").trim();
    }

    // Replace spaces with "Hair Space"
    pattern = pattern.replaceAll(" ", "\u200A");
    // Build a spannable so that the am/pm will be formatted
    int amPmPos = pattern.indexOf('a');
    if (amPmPos == -1) {
        return pattern;
    }

    final Resources resources = context.getResources();
    final float amPmProportion = resources.getFraction(R.fraction.ampm_font_size_scale, 1, 1);
    final Spannable sp = new SpannableString(pattern);
    sp.setSpan(new RelativeSizeSpan(amPmProportion), amPmPos, amPmPos + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sp.setSpan(new StyleSpan(Typeface.NORMAL), amPmPos, amPmPos + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sp.setSpan(new TypefaceSpan("sans-serif"), amPmPos, amPmPos + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Make the font smaller for locales with long am/pm strings.
    if (Utils.isAmPmStringLong()) {
        final float proportion = resources.getFraction(R.fraction.reduced_clock_font_size_scale, 1, 1);
        sp.setSpan(new RelativeSizeSpan(proportion), 0, pattern.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return sp;
}

From source file:com.juick.android.ThreadActivity.java

public void onReplySelected(final JuickMessage msg) {
    selectedReply = msg;/*from  ww w. j  ava  2 s .c o m*/
    rid = msg.getRID();
    if (rid > 0) {
        SpannableStringBuilder ssb = new SpannableStringBuilder();
        String inreplyto = getResources().getString(R.string.In_reply_to_) + " ";
        ssb.append(inreplyto).append(msg.Text);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, inreplyto.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvReplyTo.setText(ssb);
        setHeight(replyToContainer, ActionBar.LayoutParams.WRAP_CONTENT);
        showThread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tf.showThread(msg, false);
            }
        });
    } else {
        setHeight(replyToContainer, 0);
    }
}

From source file:com.ruesga.rview.tasks.AsyncTextDiffProcessor.java

private CharSequence processHighlightTabs(CharSequence text) {
    if (!mHighlightTabs || !text.toString().contains(StringHelper.NON_PRINTABLE_CHAR)) {
        return text;
    }/*from  w  w  w  .  j  a  va  2 s . c om*/

    int color = ContextCompat.getColor(mContext, R.color.diffHighlightColor);
    SpannableStringBuilder ssb = new SpannableStringBuilder(text);
    String line = text.toString();
    int index = line.length();
    while ((index = line.lastIndexOf(StringHelper.NON_PRINTABLE_CHAR, index)) != -1) {
        ssb.replace(index, index + 1, "\u00BB    ");
        ssb.setSpan(new ForegroundColorSpan(color), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(new StyleSpan(Typeface.BOLD), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        index--;
    }
    return ssb;
}

From source file:com.flipzu.flipzu.Recorder.java

@Override
public void onCommentsReceived(Hashtable<String, String>[] comments) {
    debug.logV(TAG, "onCommentsReceived");

    final LinearLayout cc = (LinearLayout) findViewById(R.id.comments_container);

    /* cleanup comments first */
    cc.removeAllViews();/*from   w w w .  j  a v a2  s  .c  o  m*/

    /* get pixel values for various DIPs */
    final float scale = getResources().getDisplayMetrics().density;
    //      final int pixel_10 = 10 / (int) (scale + 0.5f);
    final int pixel_5 = 5 / (int) (scale + 0.5f);
    //      final int pixel_30 = 30 / (int) (scale + 0.5f);
    final LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    if (comments != null && comments.length > 0) {

        for (int i = 0; i < comments.length; i++) {

            LinearLayout cl = new LinearLayout(Recorder.this);
            cl.setOrientation(LinearLayout.HORIZONTAL);
            cl.setPadding(0, 0, 0, pixel_5);

            debug.logD(TAG, "Refresher comment " + comments[i]);

            /* comment */
            TextView comment_tv = new TextView(Recorder.this);
            comment_tv.setLayoutParams(params);
            comment_tv.setText(comments[i].get("username") + ": " + comments[i].get("comment"),
                    TextView.BufferType.SPANNABLE);
            comment_tv.setTextColor(Color.parseColor("#656565"));
            Spannable comment_span = (Spannable) comment_tv.getText();
            comment_span.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
                    comment_tv.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            comment_span.setSpan(new ForegroundColorSpan(Color.parseColor("#182e5b")), 0,
                    comments[i].get("username").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            comment_tv.setText(comment_span);
            cl.addView(comment_tv);

            cc.addView(cl);

        }

    } else {
        if (mState == recorderState.RECORDING) {
            String msg = "You're LIVE! Your broadcast can be heard at http://flipzu.com/" + mUser.getUsername();
            showFlipzuTipsOffline(cc, params, msg);
        } else {
            String msg = "Pick a good and descriptive broadcast title. A great title will attract more listeners!";
            showFlipzuTipsOffline(cc, params, msg);
            msg = "You can disable sharing in Twitter and Facebook by clicking the logo buttons. This is great for testing.";
            showFlipzuTipsOffline(cc, params, msg);
            msg = "Press the \"Start Broadcast\" button and let them hear you!";
            showFlipzuTipsOffline(cc, params, msg);
        }
    }
}