Example usage for android.text SpannableStringBuilder SpannableStringBuilder

List of usage examples for android.text SpannableStringBuilder SpannableStringBuilder

Introduction

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

Prototype

public SpannableStringBuilder() 

Source Link

Document

Create a new SpannableStringBuilder with empty contents

Usage

From source file:cn.suishen.email.activity.MessageViewFragmentBase.java

protected void updateHeaderView(Message message) {
    mSubjectView.setText(message.mSubject);
    final Address from = Address.unpackFirst(message.mFrom);

    // Set sender address/display name
    // Note we set " " for empty field, so TextView's won't get squashed.
    // Otherwise their height will be 0, which breaks the layout.
    if (from != null) {
        final String fromFriendly = from.toFriendly();
        final String fromAddress = from.getAddress();
        mFromNameView.setText(fromFriendly);
        mFromAddressView.setText(fromFriendly.equals(fromAddress) ? " " : fromAddress);
    } else {/*from   w ww.ja v a  2 s  . c  o  m*/
        mFromNameView.setText(" ");
        mFromAddressView.setText(" ");
    }
    mDateTimeView.setText(DateUtils.getRelativeTimeSpanString(mContext, message.mTimeStamp).toString());

    // To/Cc/Bcc
    final Resources res = mContext.getResources();
    final SpannableStringBuilder ssb = new SpannableStringBuilder();
    final String friendlyTo = Address.toFriendly(Address.unpack(message.mTo));
    final String friendlyCc = Address.toFriendly(Address.unpack(message.mCc));
    final String friendlyBcc = Address.toFriendly(Address.unpack(message.mBcc));

    if (!TextUtils.isEmpty(friendlyTo)) {
        Utility.appendBold(ssb, res.getString(R.string.message_view_to_label));
        ssb.append(" ");
        ssb.append(friendlyTo);
    }
    if (!TextUtils.isEmpty(friendlyCc)) {
        ssb.append("  ");
        Utility.appendBold(ssb, res.getString(R.string.message_view_cc_label));
        ssb.append(" ");
        ssb.append(friendlyCc);
    }
    if (!TextUtils.isEmpty(friendlyBcc)) {
        ssb.append("  ");
        Utility.appendBold(ssb, res.getString(R.string.message_view_bcc_label));
        ssb.append(" ");
        ssb.append(friendlyBcc);
    }
    mAddressesView.setText(ssb);
}

From source file:de.tum.in.tumcampus.auxiliary.calendar.DayView.java

/**
 * Return the layout for a numbered event. Create it if not already existing
 *//*  ww w.j  av  a2s .  co m*/
private StaticLayout getEventLayout(StaticLayout[] layouts, int i, Event event, Paint paint, Rect r) {
    if (i < 0 || i >= layouts.length) {
        return null;
    }

    StaticLayout layout = layouts[i];
    // Check if we have already initialized the StaticLayout and that
    // the width hasn't changed (due to vertical resizing which causes
    // re-layout of events at min height)
    if (layout == null || r.width() != layout.getWidth()) {
        SpannableStringBuilder bob = new SpannableStringBuilder();
        if (event.title != null) {
            // MAX - 1 since we add a space
            bob.append(drawTextSanitizer(event.title.toString(), MAX_EVENT_TEXT_LEN - 1));
            bob.setSpan(new StyleSpan(Typeface.BOLD), 0, bob.length(), 0);
            bob.append(' ');
        }
        if (event.location != null) {
            bob.append(drawTextSanitizer(event.location.toString(), MAX_EVENT_TEXT_LEN - bob.length()));
        }

        paint.setColor(mEventTextColor);

        // Leave a one pixel boundary on the left and right of the rectangle for the event
        layout = new StaticLayout(bob, 0, bob.length(), new TextPaint(paint), r.width(), Alignment.ALIGN_NORMAL,
                1.0f, 0.0f, true, null, r.width());

        layouts[i] = layout;
    }
    layout.getPaint().setAlpha(mEventsAlpha);
    return layout;
}

From source file:com.android.mail.utils.NotificationUtils.java

private static SpannableStringBuilder ellipsizeStyledSenders(final Context context,
        ArrayList<SpannableString> styledSenders) {
    if (sSendersSplitToken == null) {
        sSendersSplitToken = context.getString(R.string.senders_split_token);
        sElidedPaddingToken = context.getString(R.string.elided_padding_token);
    }// w  w w .jav a  2s.c om

    SpannableStringBuilder builder = new SpannableStringBuilder();
    SpannableString prevSender = null;
    for (SpannableString sender : styledSenders) {
        if (sender == null) {
            LogUtils.e(LOG_TAG, "null sender iterating over styledSenders");
            continue;
        }
        CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
        if (SendersView.sElidedString.equals(sender.toString())) {
            prevSender = sender;
            sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken);
        } else if (builder.length() > 0
                && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) {
            prevSender = sender;
            sender = copyStyles(spans, sSendersSplitToken + sender);
        } else {
            prevSender = sender;
        }
        builder.append(sender);
    }
    return builder;
}

From source file:com.hichinaschool.flashcards.libanki.Sched.java

/**
 * Deck finished state ******************************************************
 * *****************************************
 */// w w w.ja  va 2  s . c o m

public CharSequence finishedMsg(Context context) {
    SpannableStringBuilder sb = new SpannableStringBuilder();
    sb.append(context.getString(R.string.studyoptions_congrats_finished));
    StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
    sb.setSpan(boldSpan, 0, sb.length(), 0);
    sb.append(_nextDueMsg(context));
    // sb.append("\n\n");
    // sb.append(_tomorrowDueMsg(context));
    return sb;
}

From source file:com.tct.mail.browse.ConversationItemView.java

SpannableStringBuilder elideParticipants(List<SpannableString> parts) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();
    float totalWidth = 0;
    boolean ellipsize = false;
    float width;/*from w ww .  j av  a  2  s .c o m*/
    boolean skipToHeader = false;

    // start with "To: " if we're showing recipients
    if (mDisplayedFolder.shouldShowRecipients() && !parts.isEmpty()) {
        final SpannableString toHeader = SendersView.getFormattedToHeader();
        CharacterStyle[] spans = toHeader.getSpans(0, toHeader.length(), CharacterStyle.class);
        // There is only 1 character style span; make sure we apply all the
        // styles to the paint object before measuring.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        totalWidth += sPaint.measureText(toHeader.toString());
        builder.append(toHeader);
        skipToHeader = true;
    }

    final SpannableStringBuilder messageInfoString = mHeader.messageInfoString;
    if (messageInfoString.length() > 0) {
        CharacterStyle[] spans = messageInfoString.getSpans(0, messageInfoString.length(),
                CharacterStyle.class);
        // There is only 1 character style span; make sure we apply all the
        // styles to the paint object before measuring.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // Paint the message info string to see if we lose space.
        float messageInfoWidth = sPaint.measureText(messageInfoString.toString());
        totalWidth += messageInfoWidth;
    }
    SpannableString prevSender = null;
    SpannableString ellipsizedText;
    for (SpannableString sender : parts) {
        // There may be null sender strings if there were dupes we had to remove.
        if (sender == null) {
            continue;
        }
        // No more width available, we'll only show fixed fragments.
        if (ellipsize) {
            break;
        }
        CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
        // There is only 1 character style span.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // If there are already senders present in this string, we need to
        // make sure we prepend the dividing token
        if (SendersView.sElidedString.equals(sender.toString())) {
            prevSender = sender;
            sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken);
        } else if (!skipToHeader && builder.length() > 0
                && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) {
            prevSender = sender;
            sender = copyStyles(spans, sSendersSplitToken + sender);
        } else {
            prevSender = sender;
            skipToHeader = false;
        }
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        //TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD_S
        // Measure the width of the current sender and make sure we have space
        width = (int) sPaint.measureText(sender.toString());
        if (width + totalWidth > mCoordinates.sendersWidth) {
            // The text is too long, new line won't help. We have to
            // ellipsize text.
            ellipsize = true;
            width = mCoordinates.sendersWidth - totalWidth; // ellipsis width?
            ellipsizedText = copyStyles(spans, TextUtils.ellipsize(sender, sPaint, width, TruncateAt.END));
            width = (int) sPaint.measureText(ellipsizedText.toString());
        } else {
            ellipsizedText = null;
        }
        totalWidth += width;
        //TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD_E

        //[FEATURE]-Add-BEGIN by CDTS.zhonghua.tuo,05/29/2014,FR 670064
        CharSequence fragmentDisplayText;
        if (ellipsizedText != null) {
            fragmentDisplayText = ellipsizedText;
        } else {
            fragmentDisplayText = sender;
        }
        boolean filterSender = false;
        if (mField == UIProvider.LOCAL_SEARCH_ALL || mField == UIProvider.LOCAL_SEARCH_FROM) {
            filterSender = true;
        }
        if (mQueryText != null && filterSender) {
            fragmentDisplayText = TextUtilities.highlightTermsInText(fragmentDisplayText.toString(),
                    mQueryText);
        }
        //[FEATURE]-Add-END by CDTS.zhonghua.tuo
        builder.append(fragmentDisplayText);
    }
    mHeader.styledMessageInfoStringOffset = builder.length();
    builder.append(messageInfoString);
    return builder;
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

private void showIdentityDialog(boolean informationOnly, int titleId) {
    String fingerprint;/* ww w .jav a 2s.  c  om*/
    String uid;

    PGPPublicKeyRing publicKey = UsersProvider.getPublicKey(getActivity(), mUserJID, false);
    if (publicKey != null) {
        PGPPublicKey pk = PGP.getMasterKey(publicKey);
        fingerprint = PGP.formatFingerprint(PGP.getFingerprint(pk));
        uid = PGP.getUserId(pk, null); // TODO server!!!
    } else {
        // FIXME using another string
        fingerprint = uid = getString(R.string.peer_unknown);
    }

    SpannableStringBuilder text = new SpannableStringBuilder();
    text.append(getString(R.string.text_invitation1)).append('\n');

    Contact c = mConversation.getContact();
    if (c != null) {
        text.append(c.getName()).append(" <").append(c.getNumber()).append('>');
    } else {
        int start = text.length() - 1;
        text.append(uid);
        text.setSpan(MessageUtils.STYLE_BOLD, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    text.append('\n').append(getString(R.string.text_invitation2)).append('\n');

    int start = text.length() - 1;
    text.append(fingerprint);
    text.setSpan(MessageUtils.STYLE_BOLD, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(getActivity()).setMessage(text);

    if (informationOnly) {
        builder.setTitle(titleId);
    } else {
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // hide warning bar
                hideWarning();

                switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    // trust new key
                    trustKeyChange();
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    // block user immediately
                    setPrivacy(PRIVACY_BLOCK);
                    break;
                }
            }
        };
        builder.setTitle(titleId).setPositiveButton(R.string.button_accept, listener)
                .setNegativeButton(R.string.button_block, listener);
    }

    builder.show();
}

From source file:android.app.Activity.java

/**
 * Select the default key handling for this activity.  This controls what
 * will happen to key events that are not otherwise handled.  The default
 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
 * floor. Other modes allow you to launch the dialer
 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
 * menu without requiring the menu key be held down
 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL} 
 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
 * //from w w w.  java 2  s.com
 * <p>Note that the mode selected here does not impact the default
 * handling of system keys, such as the "back" and "menu" keys, and your
 * activity and its views always get a first chance to receive and handle
 * all application keys.
 * 
 * @param mode The desired default key mode constant.
 * 
 * @see #DEFAULT_KEYS_DISABLE
 * @see #DEFAULT_KEYS_DIALER
 * @see #DEFAULT_KEYS_SHORTCUT
 * @see #DEFAULT_KEYS_SEARCH_LOCAL
 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
 * @see #onKeyDown
 */
public final void setDefaultKeyMode(int mode) {
    mDefaultKeyMode = mode;

    // Some modes use a SpannableStringBuilder to track & dispatch input events
    // This list must remain in sync with the switch in onKeyDown()
    switch (mode) {
    case DEFAULT_KEYS_DISABLE:
    case DEFAULT_KEYS_SHORTCUT:
        mDefaultKeySsb = null; // not used in these modes
        break;
    case DEFAULT_KEYS_DIALER:
    case DEFAULT_KEYS_SEARCH_LOCAL:
    case DEFAULT_KEYS_SEARCH_GLOBAL:
        mDefaultKeySsb = new SpannableStringBuilder();
        Selection.setSelection(mDefaultKeySsb, 0);
        break;
    default:
        throw new IllegalArgumentException();
    }
}

From source file:cgeo.geocaching.CacheDetailActivity.java

static void updateCacheLists(final View view, final Geocache cache, final Resources res) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();
    for (final Integer listId : cache.getLists()) {
        if (builder.length() > 0) {
            builder.append(", ");
        }// ww  w .j a v a 2  s .  c  o  m
        appendClickableList(builder, view, listId);
    }
    builder.insert(0, res.getString(R.string.list_list_headline) + " ");
    final TextView offlineLists = ButterKnife.findById(view, R.id.offline_lists);
    offlineLists.setText(builder);
    offlineLists.setMovementMethod(LinkMovementMethod.getInstance());
}