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.android.mail.utils.NotificationUtils.java

/**
 * Sets the bigtext for a notification for a single new conversation
 *
 * @param context/*from  w  w  w . ja v  a  2  s  .c o  m*/
 * @param subject Subject of the new message that triggered the notification
 * @param message the {@link Message} to be displayed.
 * @return a {@link CharSequence} suitable for use in
 *         {@link android.support.v4.app.NotificationCompat.BigTextStyle}
 */
private static CharSequence getSingleMessageBigText(Context context, String subject, final Message message) {

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

    final String snippet = getMessageBodyWithoutElidedText(message);

    // Change multiple newlines (with potential white space between), into a single new line
    final String collapsedSnippet = !TextUtils.isEmpty(snippet) ? snippet.replaceAll("\\n\\s+", "\n") : "";

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

        return spannableString;
    } else {
        final String notificationBigTextFormat = context.getResources()
                .getString(R.string.single_new_message_notification_big_text);

        // Localizers may change the order of the parameters, look at how the format
        // string is structured.
        final boolean isSubjectFirst = notificationBigTextFormat.indexOf("%2$s") > notificationBigTextFormat
                .indexOf("%1$s");
        final String bigText = String.format(notificationBigTextFormat, subject, collapsedSnippet);
        final SpannableString spannableString = new SpannableString(bigText);

        final int subjectOffset = (isSubjectFirst ? bigText.indexOf(subject) : bigText.lastIndexOf(subject));
        spannableString.setSpan(notificationSubjectSpan, subjectOffset, subjectOffset + subject.length(), 0);

        return spannableString;
    }
}

From source file:im.vector.activity.VectorRoomActivity.java

/**
 * Refresh the notifications area./* www. j  a v  a 2 s . co  m*/
 */
private void refreshNotificationsArea() {
    // sanity check
    // might happen when the application is logged out
    if ((null == mSession.getDataHandler()) || (null == mRoom)) {
        return;
    }

    int iconId = -1;
    int textColor = -1;
    boolean isAreaVisible = false;
    SpannableString text = new SpannableString("");
    boolean hasUnsentEvent = false;

    // remove any listeners
    mNotificationTextView.setOnClickListener(null);
    mNotificationIconImageView.setOnClickListener(null);

    //  no network
    if (!Matrix.getInstance(this).isConnected()) {
        isAreaVisible = true;
        iconId = R.drawable.error;
        textColor = R.color.vector_fuchsia_color;
        text = new SpannableString(getResources().getString(R.string.room_offline_notification));
    } else {
        Collection<Event> undeliveredEvents = mSession.getDataHandler().getStore()
                .getUndeliverableEvents(mRoom.getRoomId());
        if ((null != undeliveredEvents) && (undeliveredEvents.size() > 0)) {
            hasUnsentEvent = true;
            isAreaVisible = true;
            iconId = R.drawable.error;

            String part1 = getResources().getString(R.string.room_unsent_messages_notification);
            String part2 = getResources().getString(R.string.room_prompt_resent);

            text = new SpannableString(part1 + " " + part2);
            text.setSpan(new UnderlineSpan(), part1.length() + 1, part1.length() + part2.length() + 1, 0);
            textColor = R.color.vector_fuchsia_color;

            mNotificationTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mVectorMessageListFragment.resendUnsentMessages();
                    refreshNotificationsArea();
                }
            });
        } else if ((null != mIsScrolledToTheBottom) && (!mIsScrolledToTheBottom)) {
            isAreaVisible = true;

            int unreadCount = 0;

            RoomSummary summary = mRoom.getDataHandler().getStore().getSummary(mRoom.getRoomId());

            if (null != summary) {
                unreadCount = mRoom.getDataHandler().getStore().eventsCountAfter(mRoom.getRoomId(),
                        summary.getLatestReadEventId());
            }

            if (unreadCount > 0) {
                iconId = R.drawable.newmessages;
                textColor = R.color.vector_fuchsia_color;

                if (unreadCount == 1) {
                    text = new SpannableString(
                            getResources().getString(R.string.room_new_message_notification));
                } else {
                    text = new SpannableString(
                            getResources().getString(R.string.room_new_messages_notification, unreadCount));
                }
            } else {
                iconId = R.drawable.scrolldown;
                textColor = R.color.vector_text_gray_color;

                if (!TextUtils.isEmpty(mLatestTypingMessage)) {
                    text = new SpannableString(mLatestTypingMessage);
                }
            }

            mNotificationTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mVectorMessageListFragment.scrollToBottom(0);
                }
            });

            mNotificationIconImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mVectorMessageListFragment.scrollToBottom(0);
                }
            });

        } else if (!TextUtils.isEmpty(mLatestTypingMessage)) {
            isAreaVisible = true;

            iconId = R.drawable.vector_typing;
            text = new SpannableString(mLatestTypingMessage);
            textColor = R.color.vector_text_gray_color;
        }
    }

    if (TextUtils.isEmpty(mEventId)) {
        mNotificationsArea.setVisibility(isAreaVisible ? View.VISIBLE : View.INVISIBLE);
    }

    if ((-1 != iconId) && (-1 != textColor)) {
        mNotificationIconImageView.setImageResource(iconId);
        mNotificationTextView.setText(text);
        mNotificationTextView.setTextColor(getResources().getColor(textColor));
    }

    //
    if (null != mResendUnsentMenuItem) {
        mResendUnsentMenuItem.setVisible(hasUnsentEvent);
    }

    if (null != mResendDeleteMenuItem) {
        mResendDeleteMenuItem.setVisible(hasUnsentEvent);
    }
}

From source file:com.android.ex.chips.RecipientEditTextView.java

void createMoreChipPlainText() {
    // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
    final Editable text = getText();
    int start = 0;
    int end = start;
    for (int i = 0; i < CHIP_LIMIT; i++) {
        end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
        start = end; // move to the next token and get its end.
    }/*from  w ww. j  a  v a 2s  .c om*/
    // Now, count total addresses.
    start = 0;
    final int tokenCount = countTokens(text);
    final MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
    final SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
    chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.replace(end, text.length(), chipText);
    mMoreChip = moreSpan;
}

From source file:org.de.jmg.learn._MainActivity.java

public void SetActionBarTitle() throws Exception {
    if (mainView == null)
        return;//from  w  w  w .j  av  a 2s  .  c o m
    if (_vok.getGesamtzahl() > 0) {
        String FName = "";
        if (!libString.IsNullOrEmpty(_vok.getFileName())) {
            FName = new File(_vok.getFileName()).getName();
        } else if (_vok.getURI() != null) {
            String path = lib.dumpUriMetaData(_main, _vok.getURI());
            if (path.contains(":"))
                path = path.split(":")[0];
            int li = path.lastIndexOf("/");
            if (li > -1) {
                FName = path.substring(path.lastIndexOf("/"));
            } else {
                FName = "/" + path;
            }
        } else if (!libString.IsNullOrEmpty(_vok.getURIName())) {
            FName = _vok.getURIName();
        }
        if (FName.length() > 15 && _isSmallDevice) {
            FName = FName.substring(0, 15);
        } else if (FName.length() > 30) {
            FName = FName.substring(0, 30);
        }
        String title = "" + FName + " " + getString(R.string.number) + ": " + _vok.getIndex() + "/"
                + (_vok.getVokabeln().size() - 1) + " " + getString(R.string.counter) + ": "
                + _vok.getZaehler();
        String Right = " " + _vok.AnzRichtig;
        String Wrong = " " + _vok.AnzFalsch;
        SpannableString spnTitle = new SpannableString(title);
        SpannableString spnRight = new SpannableString(Right);
        SpannableString spnWrong = new SpannableString(Wrong);
        spnRight.setSpan(new ForegroundColorSpan(Color.GREEN), 0, spnRight.length(),
                SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        spnWrong.setSpan(new ForegroundColorSpan(Color.RED), 0, spnWrong.length(),
                SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        TextView txtStatus = (TextView) (findViewById(R.id.txtStatus));
        if (txtStatus != null)
            txtStatus.setText(TextUtils.concat(spnTitle, spnRight, spnWrong));
        //getSupportActionBar().setTitle(
        //      TextUtils.concat(spnTitle, spnRight, spnWrong));

    } else {
        Log.d("Vok", "empty");
        /*
         * String title = "Learn " + "empty._vok" + " " +
         * getString(R.string.number) + ": " + _vok.getIndex() + " " +
         * getString(R.string.counter) + ": " + _vok.getZaehler(); String
         * Right = " " + _vok.AnzRichtig; String Wrong = " " + _vok.AnzFalsch;
         * SpannableString spnTitle = new SpannableString(title);
         * SpannableString spnRight = new SpannableString(Right);
         * SpannableString spnWrong = new SpannableString(Wrong);
         * spnRight.setSpan(new ForegroundColorSpan(Color.GREEN), 0,
         * spnRight.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
         * spnWrong.setSpan(new ForegroundColorSpan(Color.RED), 0,
         * spnWrong.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
         *
         * getSupportActionBar().setTitle( TextUtils.concat(spnTitle,
         * spnRight, spnWrong));
         */
    }
    resizeActionbar(0);
}

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

/**
 * Gets the title for a notification for a single new conversation
 * @param context/*from  w w  w.j  a v a2s.c  o  m*/
 * @param sender Sender of the new message that triggered the notification.
 * @param subject Subject of the new message that triggered the notification
 * @return a {@link CharSequence} suitable for use as a {@link Notification} title.
 */
private static CharSequence getSingleMessageNotificationTitle(Context context, String sender, String subject) {

    if (TextUtils.isEmpty(subject)) {
        // If the subject is empty, just set the title to the sender's information.
        return sender;
    } else {
        final String notificationTitleFormat = context.getResources()
                .getString(R.string.single_new_message_notification_title);

        // Localizers may change the order of the parameters, look at how the format
        // string is structured.
        final boolean isSubjectLast = notificationTitleFormat.indexOf("%2$s") > notificationTitleFormat
                .indexOf("%1$s");
        final String titleString = String.format(notificationTitleFormat, sender, subject);

        // Format the string so the subject is using the secondaryText style
        final SpannableString titleSpannable = new SpannableString(titleString);

        // Find the offset of the subject.
        final int subjectOffset = isSubjectLast ? titleString.lastIndexOf(subject)
                : titleString.indexOf(subject);
        final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan(context,
                R.style.NotificationSecondaryText);
        titleSpannable.setSpan(notificationSubjectSpan, subjectOffset, subjectOffset + subject.length(), 0);
        return titleSpannable;
    }
}

From source file:com.android.ex.chips.RecipientEditTextView.java

/**
 * Create the more chip. The more chip is text that replaces any chips that do not fit in the pre-defined available
 * space when the RecipientEditTextView loses focus.
 *//* w  ww  .ja v  a  2 s  . c o m*/
// Visible for testing.
/* package */void createMoreChip() {
    if (mNoChips) {
        createMoreChipPlainText();
        return;
    }
    if (!mShouldShrink)
        return;
    final ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
    if (tempMore.length > 0)
        getSpannable().removeSpan(tempMore[0]);
    final DrawableRecipientChip[] recipients = getSortedRecipients();
    if (recipients == null || recipients.length <= CHIP_LIMIT) {
        mMoreChip = null;
        return;
    }
    final Spannable spannable = getSpannable();
    final int numRecipients = recipients.length;
    final int overage = numRecipients - CHIP_LIMIT;
    final MoreImageSpan moreSpan = createMoreSpan(overage);
    mRemovedSpans = new ArrayList<DrawableRecipientChip>();
    int totalReplaceStart = 0;
    int totalReplaceEnd = 0;
    final Editable text = getText();
    for (int i = numRecipients - overage; i < recipients.length; i++) {
        mRemovedSpans.add(recipients[i]);
        if (i == numRecipients - overage)
            totalReplaceStart = spannable.getSpanStart(recipients[i]);
        if (i == recipients.length - 1)
            totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
        if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
            final int spanStart = spannable.getSpanStart(recipients[i]);
            final int spanEnd = spannable.getSpanEnd(recipients[i]);
            recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
        }
        spannable.removeSpan(recipients[i]);
    }
    if (totalReplaceEnd < text.length())
        totalReplaceEnd = text.length();
    final int end = Math.max(totalReplaceStart, totalReplaceEnd);
    final int start = Math.min(totalReplaceStart, totalReplaceEnd);
    final SpannableString chipText = new SpannableString(text.subSequence(start, end));
    chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.replace(start, end, chipText);
    mMoreChip = moreSpan;
    // If adding the +more chip goes over the limit, resize accordingly.
    if (!isPhoneQuery() && getLineCount() > mMaxLines)
        setMaxLines(getLineCount());
}

From source file:ru.valle.btc.MainActivity.java

private CharSequence getPrivateKeyTypeLabel(final KeyPair keyPair) {
    int typeWithCompression = keyPair.privateKey.type == BTCUtils.PrivateKeyInfo.TYPE_BRAIN_WALLET
            && keyPair.privateKey.isPublicKeyCompressed ? keyPair.privateKey.type + 1 : keyPair.privateKey.type;
    CharSequence keyType = getResources().getTextArray(R.array.private_keys_types)[typeWithCompression];
    SpannableString keyTypeLabel = new SpannableString(getString(R.string.private_key_type, keyType));
    int keyTypeStart = keyTypeLabel.toString().indexOf(keyType.toString());
    keyTypeLabel.setSpan(new StyleSpan(Typeface.BOLD), keyTypeStart, keyTypeStart + keyType.length(),
            SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
    if (keyPair.privateKey.type == BTCUtils.PrivateKeyInfo.TYPE_BRAIN_WALLET) {
        String compressionStrToSpan = keyType.toString().substring(keyType.toString().indexOf(',') + 2);
        int start = keyTypeLabel.toString().indexOf(compressionStrToSpan);
        if (start >= 0) {

            ClickableSpan switchPublicKeyCompressionSpan = new ClickableSpan() {
                @Override//from  w w  w .  jav  a  2  s . co  m
                public void onClick(View widget) {
                    cancelAllRunningTasks();
                    switchingCompressionTypeTask = new AsyncTask<Void, Void, KeyPair>() {

                        @Override
                        protected KeyPair doInBackground(Void... params) {
                            return new KeyPair(new BTCUtils.PrivateKeyInfo(keyPair.privateKey.type,
                                    keyPair.privateKey.privateKeyEncoded, keyPair.privateKey.privateKeyDecoded,
                                    !keyPair.privateKey.isPublicKeyCompressed));
                        }

                        @Override
                        protected void onPostExecute(KeyPair keyPair) {
                            switchingCompressionTypeTask = null;
                            onKeyPairModify(false, keyPair);
                        }
                    };
                    switchingCompressionTypeTask.execute();
                }
            };
            keyTypeLabel.setSpan(switchPublicKeyCompressionSpan, start, start + compressionStrToSpan.length(),
                    SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
        }
    }
    return keyTypeLabel;
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * handle the receipt of suggestions from the spell checker
 * colour the text in the editor as required
 * pass information to the keyboard view so it can draw the colour bar
 * initiate audio and haptic feedback as required
 *//*from   ww  w.  j a v  a  2  s.  c  o  m*/
@Override
public void onGetSuggestions(SuggestionsInfo[] results) {
    // TODO Auto-generated method stub
    int colortype = -1;
    final StringBuilder sb = new StringBuilder();

    if (updateSuggestionList) {
        updateSuggestionList = false;
        ArrayList<String> s = new ArrayList<String>();
        for (int i = 0; i < results.length; ++i) {
            final int length = results[i].getSuggestionsCount();
            for (int j = 0; j < length; ++j) {
                s.add(results[i].getSuggestionAt(j));
            }
        }
        updateSuggestionListWithSpellChecker(s);
    } else {

        for (int i = 0; i < results.length; ++i) {
            // Returned suggestions are contained in SuggestionsInfo

            final int len = results[i].getSuggestionsCount();
            sb.append("Suggestion Attribs: " + results[i].getSuggestionsAttributes());
            if ((results[i].getSuggestionsAttributes()
                    & SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) == SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) {
                sb.append("The word was found in the dictionary\n");
                mInputView.wordcompletedtype = 3;
            } else {

                if ((results[i].getSuggestionsAttributes()
                        & SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) == SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) {
                    if ((results[i].getSuggestionsAttributes()
                            & SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) == SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) {
                        colortype = 1; //yellow
                        mInputView.wordcompletedtype = 1;
                        sb.append("There are strong candidates for this word\n");
                        currentSession.nLowErrors++;
                    } else {
                        colortype = 2; //red
                        mInputView.wordcompletedtype = 2;
                        sb.append("The word looks like a typo\n");
                        currentSession.nHighErrors++;

                    }
                }

            }

            sb.append("\n--These are the suggestions--\n");
            for (int j = 0; j < len; ++j) {
                sb.append("," + results[i].getSuggestionAt(j));
            }
            sb.append(" (" + len + ")");
        }
        //Log.i("Spelling suggestions", sb.toString());

        //this comes after a word separator, hence just add 1 to the cursor
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        SpannableString text = new SpannableString(mComposingTemp);

        if (sharedPrefs.getBoolean("highlightwords", true)) {
            switch (colortype) {
            case 1:
                text.setSpan(new BackgroundColorSpan(small_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case 2:
                text.setSpan(new BackgroundColorSpan(big_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            default:
                break;
            }
        }

        if (sharedPrefs.getBoolean("autocorrect", true) && mInputView.wordcompletedtype == 1) //handle autocorrection
        {
            SpannableString autoc = autocorrect(results);
            autocorrected_words.put(autoc.toString(), text.toString()); //autocorrected word, original input
            //Log.i("Autocorrecting","Key= "+autoc.toString()+", Value= "+text.toString());
            text = autoc;
            if (sharedPrefs.getBoolean("highlightwords", true))
                text.setSpan(new BackgroundColorSpan(autocorrect), 0, text.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mInputView.wordcompletedtype = 4;
        } else //autocorrection is turned off
        {
            if (!sharedPrefs.getBoolean("autocorrect", true) && colortype >= 1) //a mistake word
            {
                //Log.i("OnGetSentenceSuggestions","Key= "+text.toString()+", Value= "+text.toString());
                //no autocorrects, just put the word in and itself as the replacement
                autocorrected_words.put(text.toString(), text.toString());
            }
        }

        if (sharedPrefs.getBoolean("vibrator", false)) {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            final int on_time = Integer.parseInt(sharedPrefs.getString("shortvibe", "35"));

            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                // Vibrate for 300 milliseconds
                v.vibrate(on_time);
                break;
            case 2: //big err
                //v.vibrate(Integer.parseInt(sharedPrefs.getString("longvibe", "300")));
                v.vibrate(new long[] { 0, on_time, 200, on_time }, -1);
                break;
            case 4: //autocorr
                v.vibrate(on_time);
                break;
            default:
                break;

            }
        }

        if (sharedPrefs.getBoolean("audio", false)) {
            final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            case 2: //big err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
                break;
            case 4: //autocorr
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            default:
                break;

            }
        }

        mInputView.invalidateAllKeys();
        ic.commitText(text, 1);
        sendKey(wordSeparatorKeyCode);
        coreEngine.resetCoreString();
        updateCandidates();
    }

}

From source file:com.eleybourn.bookcatalogue.utils.Utils.java

/**
 * Linkify partial HTML. Linkify methods remove all spans before building links, this
 * method preserves them./*w  w  w.jav a  2s. c o m*/
 * 
 * See: http://stackoverflow.com/questions/14538113/using-linkify-addlinks-combine-with-html-fromhtml
 * 
 * @param html         Partial HTML
 * @param linkifyMask   Linkify mask to use in Linkify.addLinks
 * 
 * @return            Spannable with all links
 */
public static Spannable linkifyHtml(String html, int linkifyMask) {
    // Get the spannable HTML
    Spanned text = Html.fromHtml(html);
    // Save the span details for later restoration
    URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class);

    // Build an empty spannable then add the links
    SpannableString buffer = new SpannableString(text);
    Linkify.addLinks(buffer, linkifyMask);

    // Add back the HTML spannables
    for (URLSpan span : currentSpans) {
        int end = text.getSpanEnd(span);
        int start = text.getSpanStart(span);
        buffer.setSpan(span, start, end, 0);
    }
    return buffer;
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * create a spannable string object that can be coloured from a spell checker suggestion
 * @param results//w  w  w . j av a 2s  .c om
 * @return
 */
public SpannableString autocorrect(SuggestionsInfo[] results) {
    SpannableString text = new SpannableString(results[0].getSuggestionAt(0));
    return text;
}