Example usage for android.text SpannableString SpannableString

List of usage examples for android.text SpannableString SpannableString

Introduction

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

Prototype

public SpannableString(CharSequence source) 

Source Link

Document

For the backward compatibility reasons, this constructor copies all spans including android.text.NoCopySpan .

Usage

From source file:com.tsp.clipsy.audio.RingdroidEditActivity.java

private void handleFatalError(final CharSequence errorInternalName, final CharSequence errorString,
        final Exception exception) {
    Log.i("Ringdroid", "handleFatalError");

    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    int failureCount = prefs.getInt(PREF_ERROR_COUNT, 0);
    final SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putInt(PREF_ERROR_COUNT, failureCount + 1);
    prefsEditor.commit();// w  ww  .  j av a  2s. c  om

    // Check if we already have a pref for whether or not we can
    // contact the server.
    int serverAllowed = prefs.getInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_UNKNOWN);

    if (serverAllowed == SERVER_ALLOWED_NO) {
        Log.i("Ringdroid", "ERR: SERVER_ALLOWED_NO");

        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    if (serverAllowed == SERVER_ALLOWED_YES) {
        Log.i("Ringdroid", "SERVER_ALLOWED_YES");

        new AlertDialog.Builder(RingdroidEditActivity.this).setTitle(R.string.alert_title_failure)
                .setMessage(errorString)
                .setPositiveButton(R.string.alert_ok_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        finish();
                        return;
                    }
                }).setCancelable(false).show();
        return;
    }

    // The number of times the user must have had a failure before
    // we'll ask them.  Defaults to 1, and each time they click "Later"
    // we double and add 1.
    final int allowServerCheckIndex = prefs.getInt(PREF_ERR_SERVER_CHECK, 1);
    if (failureCount < allowServerCheckIndex) {
        Log.i("Ringdroid", "failureCount " + failureCount + " is less than " + allowServerCheckIndex);
        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    final SpannableString message = new SpannableString(
            errorString + ". " + getResources().getText(R.string.error_server_prompt));
    Linkify.addLinks(message, Linkify.ALL);

    AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.alert_title_failure)
            .setMessage(message).setPositiveButton(R.string.server_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_YES);
                    prefsEditor.commit();
                    finish();
                    return;
                }
            }).setNeutralButton(R.string.server_later, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_CHECK, 1 + allowServerCheckIndex * 2);
                    Log.i("Ringdroid",
                            "Won't check again until " + (1 + allowServerCheckIndex * 2) + " errors.");
                    prefsEditor.commit();
                    finish();
                }
            }).setNegativeButton(R.string.server_never, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_NO);
                    prefsEditor.commit();
                    finish();
                }
            }).setCancelable(false).show();

    // Make links clicky
    ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:com.android.contacts.common.list.ContactListItemView.java

/**
 * Sets phone number for a list item. This takes care of number highlighting if the highlight
 * mask exists./*from w  w  w .j a va  2  s .c  om*/
 */
public void setPhoneNumber(String text, String countryIso) {
    if (text == null) {
        if (mDataView != null) {
            mDataView.setVisibility(View.GONE);
        }
    } else {
        getDataView();

        // TODO: Format number using PhoneNumberUtils.formatNumber before assigning it to
        // mDataView. Make sure that determination of the highlight sequences are done only
        // after number formatting.

        // Sets phone number texts for display after highlighting it, if applicable.
        // CharSequence textToSet = text;
        final SpannableString textToSet = new SpannableString(text);

        if (mNumberHighlightSequence.size() != 0) {
            final HighlightSequence highlightSequence = mNumberHighlightSequence.get(0);
            mTextHighlighter.applyMaskingHighlight(textToSet, highlightSequence.start, highlightSequence.end);
        }

        setMarqueeText(mDataView, textToSet);
        mDataView.setVisibility(VISIBLE);

        // We have a phone number as "mDataView" so make it always LTR and VIEW_START
        mDataView.setTextDirection(View.TEXT_DIRECTION_LTR);
        mDataView.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
    }
}

From source file:com.jecelyin.editor.v2.core.text.TextUtils.java

/**
 * Returns a CharSequence concatenating the specified CharSequences,
 * retaining their spans if any.//from w w w  .j a v a2  s  . com
 */
public static CharSequence concat(CharSequence... text) {
    if (text.length == 0) {
        return "";
    }

    if (text.length == 1) {
        return text[0];
    }

    boolean spanned = false;
    for (int i = 0; i < text.length; i++) {
        if (text[i] instanceof Spanned) {
            spanned = true;
            break;
        }
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length; i++) {
        sb.append(text[i]);
    }

    if (!spanned) {
        return sb.toString();
    }

    SpannableString ss = new SpannableString(sb);
    int off = 0;
    for (int i = 0; i < text.length; i++) {
        int len = text[i].length();

        if (text[i] instanceof Spanned) {
            copySpansFrom((Spanned) text[i], 0, len, Object.class, ss, off);
        }

        off += len;
    }

    return new SpannedString(ss);
}

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

private static SpannableString copyStyles(CharacterStyle[] spans, CharSequence newText) {
    SpannableString s = new SpannableString(newText);
    if (spans != null && spans.length > 0) {
        s.setSpan(spans[0], 0, s.length(), 0);
    }// www .  j  a v a  2 s  . com
    return s;
}

From source file:com.android.contacts.common.list.ContactListItemView.java

private void setMarqueeText(TextView textView, CharSequence text) {
    if (getTextEllipsis() == TruncateAt.MARQUEE) {
        // To show MARQUEE correctly (with END effect during non-active state), we need
        // to build Spanned with MARQUEE in addition to TextView's ellipsize setting.
        final SpannableString spannable = new SpannableString(text);
        spannable.setSpan(TruncateAt.MARQUEE, 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannable);/*from   www .j a  v a2s .c  o  m*/
    } else {
        textView.setText(text);
    }
}

From source file:com.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java

protected static CharSequence buildTickerMessage(Context context, String address, String subject, String body) {
    String displayAddress = Contact.get(address, true).getName();

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

    int offset = buf.length();
    if (!TextUtils.isEmpty(subject)) {
        subject = subject.replace('\n', ' ').replace('\r', ' ');
        buf.append(subject);/*from   www .j av  a  2  s.  c o m*/
        buf.append(' ');
    }

    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;
}

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

/**
 * Sets the bigtext for a notification for a single new conversation
 *
 * @param context/*from   w  w w . j  a v  a 2 s. co  m*/
 * @param senders Sender of the new message that triggered the notification.
 * @param subject Subject of the new message that triggered the notification
 * @param snippet Snippet of the new message that triggered the notification
 * @return a {@link CharSequence} suitable for use in
 *         {@link android.support.v4.app.NotificationCompat.BigTextStyle}
 */
private static CharSequence getSingleMessageInboxLine(Context context, String senders, String subject,
        String snippet) {
    // TODO(cwren) finish this step toward commmon code with getSingleMessageBigText

    final String subjectSnippet = !TextUtils.isEmpty(subject) ? subject : snippet;

    final TextAppearanceSpan notificationPrimarySpan = new TextAppearanceSpan(context,
            R.style.NotificationPrimaryText);

    if (TextUtils.isEmpty(senders)) {
        // If the senders are empty, just use the subject/snippet.
        return subjectSnippet;
    } else if (TextUtils.isEmpty(subjectSnippet)) {
        // If the subject/snippet is empty, just use the senders.
        final SpannableString spannableString = new SpannableString(senders);
        spannableString.setSpan(notificationPrimarySpan, 0, senders.length(), 0);

        return spannableString;
    } else {
        final String formatString = context.getResources()
                .getString(R.string.multiple_new_message_notification_item);
        final TextAppearanceSpan notificationSecondarySpan = new TextAppearanceSpan(context,
                R.style.NotificationSecondaryText);

        // senders is already individually unicode wrapped so it does not need to be done here
        final String instantiatedString = String.format(formatString, senders,
                BIDI_FORMATTER.unicodeWrap(subjectSnippet));

        final SpannableString spannableString = new SpannableString(instantiatedString);

        final boolean isOrderReversed = formatString.indexOf("%2$s") < formatString.indexOf("%1$s");
        final int primaryOffset = (isOrderReversed ? instantiatedString.lastIndexOf(senders)
                : instantiatedString.indexOf(senders));
        final int secondaryOffset = (isOrderReversed ? instantiatedString.lastIndexOf(subjectSnippet)
                : instantiatedString.indexOf(subjectSnippet));
        spannableString.setSpan(notificationPrimarySpan, primaryOffset, primaryOffset + senders.length(), 0);
        spannableString.setSpan(notificationSecondarySpan, secondaryOffset,
                secondaryOffset + subjectSnippet.length(), 0);
        return spannableString;
    }
}

From source file:mobi.omegacentauri.ptimer.PTimerEditActivity.java

private void handleFatalError(final CharSequence errorInternalName, final CharSequence errorString,
        final Exception exception) {
    Log.i("Ringdroid", "handleFatalError");

    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    int failureCount = prefs.getInt(PREF_ERROR_COUNT, 0);
    final SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putInt(PREF_ERROR_COUNT, failureCount + 1);
    prefsEditor.commit();//from  w  w  w . j  av  a2s  .  c o  m

    // Check if we already have a pref for whether or not we can
    // contact the server.
    int serverAllowed = prefs.getInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_UNKNOWN);

    if (serverAllowed == SERVER_ALLOWED_NO) {
        Log.i("Ringdroid", "ERR: SERVER_ALLOWED_NO");

        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    if (serverAllowed == SERVER_ALLOWED_YES) {
        Log.i("Ringdroid", "SERVER_ALLOWED_YES");

        new AlertDialog.Builder(PTimerEditActivity.this).setTitle(R.string.alert_title_failure)
                .setMessage(errorString)
                .setPositiveButton(R.string.alert_ok_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        sendErrToServerAndFinish(errorInternalName, exception);
                        return;
                    }
                }).setCancelable(false).show();
        return;
    }

    // The number of times the user must have had a failure before
    // we'll ask them.  Defaults to 1, and each time they click "Later"
    // we double and add 1.
    final int allowServerCheckIndex = prefs.getInt(PREF_ERR_SERVER_CHECK, 1);
    if (failureCount < allowServerCheckIndex) {
        Log.i("Ringdroid", "failureCount " + failureCount + " is less than " + allowServerCheckIndex);
        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    final SpannableString message = new SpannableString(
            errorString + ". " + getResources().getText(R.string.error_server_prompt));
    Linkify.addLinks(message, Linkify.ALL);

    AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.alert_title_failure)
            .setMessage(message).setPositiveButton(R.string.server_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_YES);
                    prefsEditor.commit();
                    sendErrToServerAndFinish(errorInternalName, exception);
                }
            }).setNeutralButton(R.string.server_later, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_CHECK, 1 + allowServerCheckIndex * 2);
                    Log.i("Ringdroid",
                            "Won't check again until " + (1 + allowServerCheckIndex * 2) + " errors.");
                    prefsEditor.commit();
                    finish();
                }
            }).setNegativeButton(R.string.server_never, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_NO);
                    prefsEditor.commit();
                    finish();
                }
            }).setCancelable(false).show();

    // Make links clicky
    ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private final void addCallAndContactMenuItems(ContextMenu menu, MsgListMenuClickListener l,
        MessageItem msgItem) {/*from   ww w .j  a  v a2  s  .co m*/
    if (TextUtils.isEmpty(msgItem.mBody)) {
        return;
    }
    SpannableString msg = new SpannableString(msgItem.mBody);
    Linkify.addLinks(msg, Linkify.ALL);
    ArrayList<String> uris = MessageUtils.extractUris(msg.getSpans(0, msg.length(), URLSpan.class));

    // Remove any dupes so they don't get added to the menu multiple times
    HashSet<String> collapsedUris = new HashSet<String>();
    for (String uri : uris) {
        collapsedUris.add(uri.toLowerCase());
    }
    for (String uriString : collapsedUris) {
        String prefix = null;
        int sep = uriString.indexOf(":");
        if (sep >= 0) {
            prefix = uriString.substring(0, sep);
            uriString = uriString.substring(sep + 1);
        }
        Uri contactUri = null;
        boolean knownPrefix = true;
        if ("mailto".equalsIgnoreCase(prefix)) {
            contactUri = getContactUriForEmail(uriString);
        } else if ("tel".equalsIgnoreCase(prefix)) {
            contactUri = getContactUriForPhoneNumber(uriString);
        } else {
            knownPrefix = false;
        }
        if (knownPrefix && contactUri == null) {
            Intent intent = ConversationList.createAddContactIntent(uriString);

            String addContactString = getString(R.string.menu_add_address_to_contacts, uriString);
            menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, addContactString).setOnMenuItemClickListener(l)
                    .setIntent(intent);
        }
    }
}

From source file:com.SpeechEd.SpeechEdEditActivity.java

private void handleFatalError(final CharSequence errorInternalName, final CharSequence errorString,
        final Exception exception) {
    Log.i("Speech-Ed", "handleFatalError");

    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    int failureCount = prefs.getInt(PREF_ERROR_COUNT, 0);
    final SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putInt(PREF_ERROR_COUNT, failureCount + 1);
    prefsEditor.commit();/*from   w  ww.ja v  a 2s .c  om*/

    // Check if we already have a pref for whether or not we can
    // contact the server.
    int serverAllowed = prefs.getInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_UNKNOWN);

    if (serverAllowed == SERVER_ALLOWED_NO) {
        Log.i("Speech-Ed", "ERR: SERVER_ALLOWED_NO");

        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    if (serverAllowed == SERVER_ALLOWED_YES) {
        Log.i("Speech-Ed", "SERVER_ALLOWED_YES");

        new AlertDialog.Builder(SpeechEdEditActivity.this).setTitle(R.string.alert_title_failure)
                .setMessage(errorString)
                .setPositiveButton(R.string.alert_ok_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        sendErrToServerAndFinish(errorInternalName, exception);
                        return;
                    }
                }).setCancelable(false).show();
        return;
    }

    // The number of times the user must have had a failure before
    // we'll ask them.  Defaults to 1, and each time they click "Later"
    // we double and add 1.
    final int allowServerCheckIndex = prefs.getInt(PREF_ERR_SERVER_CHECK, 1);
    if (failureCount < allowServerCheckIndex) {
        Log.i("Speech-Ed", "failureCount " + failureCount + " is less than " + allowServerCheckIndex);
        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    final SpannableString message = new SpannableString(
            errorString + ". " + getResources().getText(R.string.error_server_prompt));
    Linkify.addLinks(message, Linkify.ALL);

    AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.alert_title_failure)
            .setMessage(message).setPositiveButton(R.string.server_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_YES);
                    prefsEditor.commit();
                    sendErrToServerAndFinish(errorInternalName, exception);
                }
            }).setNeutralButton(R.string.server_later, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_CHECK, 1 + allowServerCheckIndex * 2);
                    Log.i("Speech-Ed",
                            "Won't check again until " + (1 + allowServerCheckIndex * 2) + " errors.");
                    prefsEditor.commit();
                    finish();
                }
            }).setNegativeButton(R.string.server_never, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_NO);
                    prefsEditor.commit();
                    finish();
                }
            }).setCancelable(false).show();

    // Make links clicky
    ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}