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:dev.drsoran.moloko.fragments.TaskFragment.java

private void setLocationSection(View view, final Task task) {
    String locationName = null;/*from   w  w w  .  jav  a 2  s  .c  o  m*/

    boolean showSection = !TextUtils.isEmpty(task.getLocationId());

    if (showSection) {
        // Tasks which are received by sharing from someone else may also have
        // a location ID set. But this ID is from the other ones DB. We identify
        // these tasks not by looking for the ID in our DB. These tasks do not
        // have a name and a location of 0.0, 0.0.
        //
        // @see: Issue 12: http://code.google.com/p/moloko/issues/detail?id=12
        locationName = task.getLocationName();

        showSection = !TextUtils.isEmpty(locationName) || Float.compare(task.getLongitude(), 0.0f) != 0
                || Float.compare(task.getLatitude(), 0.0f) != 0;
    }

    if (!showSection) {
        view.setVisibility(View.GONE);
    } else {
        view.setVisibility(View.VISIBLE);

        if (TextUtils.isEmpty(locationName)) {
            locationName = "Lon: " + task.getLongitude() + ", Lat: " + task.getLatitude();
        }

        boolean locationIsClickable = task.isLocationViewable();

        if (locationIsClickable) {
            final SpannableString clickableLocation = new SpannableString(locationName);
            UIUtils.initializeTitleWithTextLayoutAsLink(view, getString(R.string.task_location),
                    clickableLocation, new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            listener.onOpenLocation(task);
                        }
                    });
        } else {
            UIUtils.initializeTitleWithTextLayout(view, getString(R.string.task_location), locationName);
        }
    }
}

From source file:com.stasbar.knowyourself.Utils.java

/**
 * @param amPmRatio a value between 0 and 1 that is the ratio of the relative size of the
 *                  am/pm string to the time string
 * @return format string for 12 hours mode time
 *//*from  www .j a v  a  2s  . co  m*/
public static CharSequence get12ModeFormat(float amPmRatio) {
    String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "hma");
    if (amPmRatio <= 0) {
        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 Spannable sp = new SpannableString(pattern);
    sp.setSpan(new RelativeSizeSpan(amPmRatio), 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);

    return sp;
}

From source file:hku.fyp14017.blencode.ui.fragment.BackPackSoundFragment.java

private void updateActionModeTitle() {
    int numberOfSelectedItems = adapter.getAmountOfCheckedItems();

    if (numberOfSelectedItems == 0) {
        actionMode.setTitle(actionModeTitle);
    } else {//w  w  w .  j  av  a2s .c  om
        String appendix = multipleItemAppendixDeleteActionMode;

        if (numberOfSelectedItems == 1) {
            appendix = singleItemAppendixDeleteActionMode;
        }

        String numberOfItems = Integer.toString(numberOfSelectedItems);
        String completeTitle = actionModeTitle + " " + numberOfItems + " " + appendix;

        int titleLength = actionModeTitle.length();

        Spannable completeSpannedTitle = new SpannableString(completeTitle);
        completeSpannedTitle.setSpan(
                new ForegroundColorSpan(
                        getResources().getColor(hku.fyp14017.blencode.R.color.actionbar_title_color)),
                titleLength + 1, titleLength + (1 + numberOfItems.length()),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        actionMode.setTitle(completeSpannedTitle);
    }
}

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

/**
 * @param amPmRatio      a value between 0 and 1 that is the ratio of the relative size of the
 *                       am/pm string to the time string
 * @param includeSeconds whether or not to include seconds in the time string
 * @return format string for 12 hours mode time, not including seconds
 *//*from   www  . ja v a  2s.  c o m*/
public static CharSequence get12ModeFormat(float amPmRatio, boolean includeSeconds) {
    String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), includeSeconds ? "hmsa" : "hma");
    if (amPmRatio <= 0) {
        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 Spannable sp = new SpannableString(pattern);
    sp.setSpan(new RelativeSizeSpan(amPmRatio), 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);

    return sp;
}

From source file:com.quarterfull.newsAndroid.LoginDialogFragment.java

public static void ShowAlertDialog(String title, String text, Activity activity) {
    // Linkify the message
    final SpannableString s = new SpannableString(text);
    Linkify.addLinks(s, Linkify.ALL);/* w  w  w. j  ava 2s  .c  om*/

    AlertDialog aDialog = new AlertDialog.Builder(activity).setTitle(title).setMessage(s)
            .setPositiveButton(activity.getString(android.R.string.ok), null).create();
    aDialog.show();

    // Make the textview clickable. Must be called after show()
    ((TextView) aDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:li.barter.activities.AbstractBarterLiActivity.java

/**
 * Sets the Action bar title, using the desired {@link Typeface} loaded from {@link
 * TypefaceCache}/*  w ww. j  a v a2s. com*/
 *
 * @param title The title to set for the Action Bar
 */

public final void setActionBarTitle(final String title) {

    final SpannableString s = new SpannableString(title);
    s.setSpan(new TypefacedSpan(this, TypefaceCache.SLAB_REGULAR), 0, s.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Update the action bar title with the TypefaceSpan instance
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle(s);
}

From source file:net.gsantner.opoc.util.ContextUtils.java

/**
 * Load html into a {@link Spanned} object and set the
 * {@link TextView}'s text using {@link TextView#setText(CharSequence)}
 */// www.ja  v  a2s  .co m
public void setHtmlToTextView(TextView textView, String html) {
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(new SpannableString(htmlToSpanned(html)));
}

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

private static void handlePriority(int maxChars, String messageInfoString, ConversationInfo conversationInfo,
        ArrayList<SpannableString> styledSenders, ArrayList<String> displayableSenderNames,
        ConversationItemViewModel.SenderAvatarModel senderAvatarModel, Account account,
        final TextAppearanceSpan unreadStyleSpan, final CharacterStyle readStyleSpan,
        final boolean showToHeader) {
    final boolean shouldSelectSenders = displayableSenderNames != null;
    final boolean shouldSelectAvatar = senderAvatarModel != null;
    int maxPriorityToInclude = -1; // inclusive
    int numCharsUsed = messageInfoString.length(); // draft, number drafts,
                                                   // count
    int numSendersUsed = 0;
    int numCharsToRemovePerWord = 0;
    int maxFoundPriority = 0;
    if (numCharsUsed > maxChars) {
        numCharsToRemovePerWord = numCharsUsed - maxChars;
    }//from  w  w w.j  av  a 2  s  .  c o  m

    final Map<Integer, Integer> priorityToLength = PRIORITY_LENGTH_MAP_CACHE.get();
    try {
        priorityToLength.clear();
        int senderLength;
        for (ParticipantInfo info : conversationInfo.participantInfos) {
            final String senderName = info.name;
            senderLength = !TextUtils.isEmpty(senderName) ? senderName.length() : 0;
            priorityToLength.put(info.priority, senderLength);
            maxFoundPriority = Math.max(maxFoundPriority, info.priority);
        }
        while (maxPriorityToInclude < maxFoundPriority) {
            if (priorityToLength.containsKey(maxPriorityToInclude + 1)) {
                int length = numCharsUsed + priorityToLength.get(maxPriorityToInclude + 1);
                if (numCharsUsed > 0)
                    length += 2;
                // We must show at least two senders if they exist. If we don't
                // have space for both
                // then we will truncate names.
                if (length > maxChars && numSendersUsed >= 2) {
                    break;
                }
                numCharsUsed = length;
                numSendersUsed++;
            }
            maxPriorityToInclude++;
        }
    } finally {
        PRIORITY_LENGTH_MAP_CACHE.release(priorityToLength);
    }

    SpannableString spannableDisplay;
    boolean appendedElided = false;
    final Map<String, Integer> displayHash = Maps.newHashMap();
    final List<String> senderEmails = Lists.newArrayListWithExpectedSize(MAX_SENDER_COUNT);
    String firstSenderEmail = null;
    String firstSenderName = null;
    for (int i = 0; i < conversationInfo.participantInfos.size(); i++) {
        final ParticipantInfo currentParticipant = conversationInfo.participantInfos.get(i);
        final String currentEmail = currentParticipant.email;

        final String currentName = currentParticipant.name;
        String nameString = !TextUtils.isEmpty(currentName) ? currentName : "";
        if (nameString.length() == 0) {
            // if we're showing the To: header, show the object version of me.
            nameString = getMe(showToHeader /* useObjectMe */);
        }
        if (numCharsToRemovePerWord != 0) {
            nameString = nameString.substring(0, Math.max(nameString.length() - numCharsToRemovePerWord, 0));
        }

        final int priority = currentParticipant.priority;
        final CharacterStyle style = CharacterStyle
                .wrap(currentParticipant.readConversation ? readStyleSpan : unreadStyleSpan);
        if (priority <= maxPriorityToInclude) {
            spannableDisplay = new SpannableString(sBidiFormatter.unicodeWrap(nameString));
            // Don't duplicate senders; leave the first instance, unless the
            // current instance is also unread.
            int oldPos = displayHash.containsKey(currentName) ? displayHash.get(currentName) : DOES_NOT_EXIST;
            // If this sender doesn't exist OR the current message is
            // unread, add the sender.
            if (oldPos == DOES_NOT_EXIST || !currentParticipant.readConversation) {
                // If the sender entry already existed, and is right next to the
                // current sender, remove the old entry.
                if (oldPos != DOES_NOT_EXIST && i > 0 && oldPos == i - 1 && oldPos < styledSenders.size()) {
                    // Remove the old one!
                    styledSenders.set(oldPos, null);
                    if (shouldSelectSenders && !TextUtils.isEmpty(currentEmail)) {
                        senderEmails.remove(currentEmail);
                        displayableSenderNames.remove(currentName);
                    }
                }
                displayHash.put(currentName, i);
                spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0);
                styledSenders.add(spannableDisplay);
            }
        } else {
            if (!appendedElided) {
                spannableDisplay = new SpannableString(sElidedString);
                spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0);
                appendedElided = true;
                styledSenders.add(spannableDisplay);
            }
        }

        final String senderEmail = TextUtils.isEmpty(currentName) ? account.getEmailAddress()
                : TextUtils.isEmpty(currentEmail) ? currentName : currentEmail;

        if (shouldSelectSenders) {
            if (i == 0) {
                // Always add the first sender!
                firstSenderEmail = senderEmail;
                firstSenderName = currentName;
            } else {
                if (!Objects.equal(firstSenderEmail, senderEmail)) {
                    int indexOf = senderEmails.indexOf(senderEmail);
                    if (indexOf > -1) {
                        senderEmails.remove(indexOf);
                        displayableSenderNames.remove(indexOf);
                    }
                    senderEmails.add(senderEmail);
                    displayableSenderNames.add(currentName);
                    if (senderEmails.size() > MAX_SENDER_COUNT) {
                        senderEmails.remove(0);
                        displayableSenderNames.remove(0);
                    }
                }
            }
        }

        // if the corresponding message from this participant is unread and no sender avatar
        // is yet chosen, choose this one
        if (shouldSelectAvatar && senderAvatarModel.isNotPopulated() && !currentParticipant.readConversation) {
            senderAvatarModel.populate(currentName, senderEmail);
        }
    }

    // always add the first sender to the display
    if (shouldSelectSenders && !TextUtils.isEmpty(firstSenderEmail)) {
        if (displayableSenderNames.size() < MAX_SENDER_COUNT) {
            displayableSenderNames.add(0, firstSenderName);
        } else {
            displayableSenderNames.set(0, firstSenderName);
        }
    }

    // if all messages in the thread were read, we must search for an appropriate avatar
    if (shouldSelectAvatar && senderAvatarModel.isNotPopulated()) {
        // search for the last sender that is not the current account
        for (int i = conversationInfo.participantInfos.size() - 1; i >= 0; i--) {
            final ParticipantInfo participant = conversationInfo.participantInfos.get(i);
            // empty name implies it is the current account and should not be chosen
            if (!TextUtils.isEmpty(participant.name)) {
                // use the participant name in place of unusable email addresses
                final String senderEmail = TextUtils.isEmpty(participant.email) ? participant.name
                        : participant.email;
                senderAvatarModel.populate(participant.name, senderEmail);
                break;
            }
        }

        // if we still don't have an avatar, the account is emailing itself
        if (senderAvatarModel.isNotPopulated()) {
            senderAvatarModel.populate(account.getDisplayName(), account.getEmailAddress());
        }
    }
}

From source file:org.thoughtcrime.SMP.notifications.MessageNotifier.java

private static void appendPushNotificationState(Context context, MasterSecret masterSecret,
        NotificationState notificationState, Cursor cursor) {
    if (masterSecret != null)
        return;// w  ww  . ja v  a2  s  .c o m

    PushDatabase.Reader reader = null;
    TextSecureEnvelope envelope;

    try {
        reader = DatabaseFactory.getPushDatabase(context).readerFor(cursor);

        while ((envelope = reader.getNext()) != null) {
            Recipients recipients = RecipientFactory.getRecipientsFromString(context, envelope.getSource(),
                    false);
            Recipient recipient = recipients.getPrimaryRecipient();
            long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
            SpannableString body = new SpannableString(
                    context.getString(R.string.MessageNotifier_encrypted_message));
            body.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, body.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            if (!recipients.isMuted()) {
                notificationState.addNotification(
                        new NotificationItem(recipient, recipients, null, threadId, body, null, 0));
            }
        }
    } finally {
        if (reader != null)
            reader.close();
    }
}

From source file:com.coinblesk.client.utils.UIUtils.java

public static SpannableString toFriendlyAmountString(Context context, TransactionWrapper transaction) {
    StringBuffer friendlyAmount = new StringBuffer();

    MonetaryFormat formatter = getMoneyFormat(context);
    String btcCode = formatter.code();
    String scaledAmount = formatter.noCode().format(transaction.getAmount()).toString();
    friendlyAmount.append(scaledAmount).append(" ");
    final int coinLength = friendlyAmount.length();

    friendlyAmount.append(btcCode).append(" ");
    final int codeLength = friendlyAmount.length();

    ExchangeRate exchangeRate = transaction.getTransaction().getExchangeRate();
    if (exchangeRate != null) {
        Fiat fiat = exchangeRate.coinToFiat(transaction.getAmount());
        friendlyAmount.append("~ " + fiat.toFriendlyString());
        friendlyAmount.append(System.getProperty("line.separator") + "(1 BTC = "
                + exchangeRate.fiat.toFriendlyString() + " as of now)");
    }//from w  w w  .ja v  a  2  s . c o  m
    final int amountLength = friendlyAmount.length();

    SpannableString friendlySpannable = new SpannableString(friendlyAmount);
    friendlySpannable.setSpan(new RelativeSizeSpan(2), 0, coinLength, 0);
    friendlySpannable.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.colorAccent)),
            coinLength, codeLength, 0);
    friendlySpannable.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.main_color_400)),
            codeLength, amountLength, 0);
    return friendlySpannable;

}