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(CharSequence text) 

Source Link

Document

Create a new SpannableStringBuilder containing a copy of the specified text, including its spans if any.

Usage

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

private void calculateTextsAndBitmaps() {
    startTimer(PERF_TAG_CALCULATE_TEXTS_BITMAPS);

    if (mCheckedConversationSet != null) {
        setChecked(mCheckedConversationSet.contains(mHeader.conversation));
    }/*from  w  ww .j a  v a  2s  .c  o  m*/
    mHeader.gadgetMode = mGadgetMode;

    updateBackground();

    mHeader.hasDraftMessage = mHeader.conversation.numDrafts() > 0;

    // Parse senders fragments.
    if (mHeader.preserveSendersText) {
        // This is a special view that doesn't need special sender formatting
        mHeader.sendersDisplayText = new SpannableStringBuilder(mHeader.sendersText);
        loadImages();
    } else if (mHeader.conversation.conversationInfo != null) {
        Context context = getContext();
        mHeader.messageInfoString = SendersView.createMessageInfo(context, mHeader.conversation, true);
        final int maxChars = ConversationItemViewCoordinates.getSendersLength(context,
                mHeader.conversation.hasAttachments);

        mHeader.mSenderAvatarModel.clear();
        mHeader.displayableNames.clear();
        mHeader.styledNames.clear();

        SendersView.format(context, mHeader.conversation.conversationInfo, mHeader.messageInfoString.toString(),
                maxChars, mHeader.styledNames, mHeader.displayableNames, mHeader.mSenderAvatarModel, mAccount,
                mDisplayedFolder.shouldShowRecipients(), true);

        // If we have displayable senders, load their thumbnails
        loadImages();
    } else {
        LogUtils.wtf(LOG_TAG, "Null conversationInfo");
    }

    if (mHeader.isLayoutValid()) {
        pauseTimer(PERF_TAG_CALCULATE_TEXTS_BITMAPS);
        return;
    }
    startTimer(PERF_TAG_CALCULATE_FOLDERS);

    pauseTimer(PERF_TAG_CALCULATE_FOLDERS);

    // Paper clip icon.
    mHeader.paperclip = null;
    if (mHeader.conversation.hasAttachments) {
        mHeader.paperclip = ATTACHMENT;
    }

    startTimer(PERF_TAG_CALCULATE_SENDER_SUBJECT);

    pauseTimer(PERF_TAG_CALCULATE_SENDER_SUBJECT);
    pauseTimer(PERF_TAG_CALCULATE_TEXTS_BITMAPS);
}

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

private void showQRCodePopupForAddress(final String address) {
    DisplayMetrics dm = getResources().getDisplayMetrics();
    final int screenSize = Math.min(dm.widthPixels, dm.heightPixels);
    final String uriStr = SCHEME_BITCOIN + address;
    new AsyncTask<Void, Void, Bitmap>() {

        @Override/*from  w  w w .  j  a va 2s .  c  o m*/
        protected Bitmap doInBackground(Void... params) {
            return QRCode.getMinimumQRCode(uriStr, ErrorCorrectLevel.M).createImage(screenSize / 2);
        }

        @Override
        protected void onPostExecute(final Bitmap bitmap) {
            if (bitmap != null) {
                View view = getLayoutInflater().inflate(R.layout.address_qr, mainLayout, false);
                if (view != null) {
                    final ImageView qrView = (ImageView) view.findViewById(R.id.qr_code_image);
                    qrView.setImageBitmap(bitmap);

                    final TextView bitcoinProtocolLinkView = (TextView) view.findViewById(R.id.link1);
                    SpannableStringBuilder labelUri = new SpannableStringBuilder(uriStr);
                    ClickableSpan urlSpan = new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(uriStr));
                            try {
                                startActivity(intent);
                            } catch (Exception e) {
                                Toast.makeText(MainActivity.this, R.string.no_apps_to_view_url,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    };
                    labelUri.setSpan(urlSpan, 0, labelUri.length(),
                            SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
                    bitcoinProtocolLinkView.setText(labelUri);
                    bitcoinProtocolLinkView.setMovementMethod(LinkMovementMethod.getInstance());

                    final TextView blockexplorerLinkView = (TextView) view.findViewById(R.id.link2);
                    SpannableStringBuilder blockexplorerLinkText = new SpannableStringBuilder(
                            "blockexplorer.com");
                    setUrlSpanForAddress("blockexplorer.com", address, blockexplorerLinkText);
                    blockexplorerLinkView.setText(blockexplorerLinkText);
                    blockexplorerLinkView.setMovementMethod(LinkMovementMethod.getInstance());

                    final TextView blockchainLinkView = (TextView) view.findViewById(R.id.link3);
                    SpannableStringBuilder blockchainLinkText = new SpannableStringBuilder("blockchain.info");
                    setUrlSpanForAddress("blockchain.info", address, blockchainLinkText);
                    blockchainLinkView.setText(blockchainLinkText);
                    blockchainLinkView.setMovementMethod(LinkMovementMethod.getInstance());

                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(address);
                    builder.setView(view);
                    if (systemSupportsPrint()) {
                        builder.setPositiveButton(R.string.print, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Renderer.printQR(MainActivity.this, SCHEME_BITCOIN + address);
                            }
                        });
                        builder.setNegativeButton(android.R.string.cancel, null);
                    } else {
                        builder.setPositiveButton(android.R.string.ok, null);
                    }

                    builder.show();
                }
            }
        }
    }.execute();
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

private void displayPageNumber(int pageNumber) {

    String pageString;// w w w .  j av a 2  s  .  c  o m

    if (!config.isScrollingEnabled() && pageNumber > 0) {
        pageString = Integer.toString(pageNumber) + "\n";
    } else {
        pageString = "\n";
    }

    SpannableStringBuilder builder = new SpannableStringBuilder(pageString);
    builder.setSpan(new CenterSpan(), 0, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    pageNumberView.setTextColor(config.getTextColor());
    pageNumberView.setTextSize(config.getTextSize());

    pageNumberView.setTypeface(config.getDefaultFontFamily().getDefaultTypeface());

    pageNumberView.setText(builder);
    pageNumberView.invalidate();
}

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

private static void configureLatestEventInfoFromConversation(final Context context, final Account account,
        final FolderPreferences folderPreferences, final NotificationCompat.Builder notification,
        final Cursor conversationCursor, final PendingIntent clickIntent, final Intent notificationIntent,
        final int unreadCount, final int unseenCount, final Folder folder, final long when) {
    final Resources res = context.getResources();
    final String notificationAccount = account.name;

    LogUtils.i(LOG_TAG, "Showing notification with unreadCount of %d and unseenCount of %d", unreadCount,
            unseenCount);/*from   ww w.  ja  v  a 2  s  . co m*/

    String notificationTicker = null;

    // Boolean indicating that this notification is for a non-inbox label.
    final boolean isInbox = folder.folderUri.fullUri.equals(account.settings.defaultInbox);

    // Notification label name for user label notifications.
    final String notificationLabelName = isInbox ? null : folder.name;

    if (unseenCount > 1) {
        // Build the string that describes the number of new messages
        final String newMessagesString = res.getString(R.string.new_messages, unseenCount);

        // Use the default notification icon
        notification
                .setLargeIcon(getDefaultNotificationIcon(context, folder, true /* multiple new messages */));

        // The ticker initially start as the new messages string.
        notificationTicker = newMessagesString;

        // The title of the notification is the new messages string
        notification.setContentTitle(newMessagesString);

        // TODO(skennedy) Can we remove this check?
        if (Utils.isRunningJellybeanOrLater()) {
            // For a new-style notification
            final int maxNumDigestItems = context.getResources()
                    .getInteger(R.integer.max_num_notification_digest_items);

            // The body of the notification is the account name, or the label name.
            notification.setSubText(isInbox ? notificationAccount : notificationLabelName);

            final NotificationCompat.InboxStyle digest = new NotificationCompat.InboxStyle(notification);

            int numDigestItems = 0;
            do {
                final Conversation conversation = new Conversation(conversationCursor);

                if (!conversation.read) {
                    boolean multipleUnreadThread = false;
                    // TODO(cwren) extract this pattern into a helper

                    Cursor cursor = null;
                    MessageCursor messageCursor = null;
                    try {
                        final Uri.Builder uriBuilder = conversation.messageListUri.buildUpon();
                        uriBuilder.appendQueryParameter(UIProvider.LABEL_QUERY_PARAMETER,
                                notificationLabelName);
                        cursor = context.getContentResolver().query(uriBuilder.build(),
                                UIProvider.MESSAGE_PROJECTION, null, null, null);
                        messageCursor = new MessageCursor(cursor);

                        String from = "";
                        String fromAddress = "";
                        if (messageCursor.moveToPosition(messageCursor.getCount() - 1)) {
                            final Message message = messageCursor.getMessage();
                            fromAddress = message.getFrom();
                            if (fromAddress == null) {
                                fromAddress = "";
                            }
                            from = getDisplayableSender(fromAddress);
                        }
                        while (messageCursor.moveToPosition(messageCursor.getPosition() - 1)) {
                            final Message message = messageCursor.getMessage();
                            if (!message.read && !fromAddress.contentEquals(message.getFrom())) {
                                multipleUnreadThread = true;
                                break;
                            }
                        }
                        final SpannableStringBuilder sendersBuilder;
                        if (multipleUnreadThread) {
                            final int sendersLength = res.getInteger(R.integer.swipe_senders_length);

                            sendersBuilder = getStyledSenders(context, conversationCursor, sendersLength,
                                    notificationAccount);
                        } else {
                            sendersBuilder = new SpannableStringBuilder(getWrappedFromString(from));
                        }
                        final CharSequence digestLine = getSingleMessageInboxLine(context,
                                sendersBuilder.toString(), conversation.subject, conversation.snippet);
                        digest.addLine(digestLine);
                        numDigestItems++;
                    } finally {
                        if (messageCursor != null) {
                            messageCursor.close();
                        }
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }
            } while (numDigestItems <= maxNumDigestItems && conversationCursor.moveToNext());
        } else {
            // The body of the notification is the account name, or the label name.
            notification.setContentText(isInbox ? notificationAccount : notificationLabelName);
        }
    } else {
        // For notifications for a single new conversation, we want to get the information from
        // the conversation

        // Move the cursor to the most recent unread conversation
        seekToLatestUnreadConversation(conversationCursor);

        final Conversation conversation = new Conversation(conversationCursor);

        Cursor cursor = null;
        MessageCursor messageCursor = null;
        boolean multipleUnseenThread = false;
        String from = null;
        try {
            final Uri uri = conversation.messageListUri.buildUpon()
                    .appendQueryParameter(UIProvider.LABEL_QUERY_PARAMETER, folder.persistentId).build();
            cursor = context.getContentResolver().query(uri, UIProvider.MESSAGE_PROJECTION, null, null, null);
            messageCursor = new MessageCursor(cursor);
            // Use the information from the last sender in the conversation that triggered
            // this notification.

            String fromAddress = "";
            if (messageCursor.moveToPosition(messageCursor.getCount() - 1)) {
                final Message message = messageCursor.getMessage();
                fromAddress = message.getFrom();
                from = getDisplayableSender(fromAddress);
                notification.setLargeIcon(getContactIcon(context, from, getSenderAddress(fromAddress), folder));
            }

            // Assume that the last message in this conversation is unread
            int firstUnseenMessagePos = messageCursor.getPosition();
            while (messageCursor.moveToPosition(messageCursor.getPosition() - 1)) {
                final Message message = messageCursor.getMessage();
                final boolean unseen = !message.seen;
                if (unseen) {
                    firstUnseenMessagePos = messageCursor.getPosition();
                    if (!multipleUnseenThread && !fromAddress.contentEquals(message.getFrom())) {
                        multipleUnseenThread = true;
                    }
                }
            }

            // TODO(skennedy) Can we remove this check?
            if (Utils.isRunningJellybeanOrLater()) {
                // For a new-style notification

                if (multipleUnseenThread) {
                    // The title of a single conversation is the list of senders.
                    int sendersLength = res.getInteger(R.integer.swipe_senders_length);

                    final SpannableStringBuilder sendersBuilder = getStyledSenders(context, conversationCursor,
                            sendersLength, notificationAccount);

                    notification.setContentTitle(sendersBuilder);
                    // For a single new conversation, the ticker is based on the sender's name.
                    notificationTicker = sendersBuilder.toString();
                } else {
                    from = getWrappedFromString(from);
                    // The title of a single message the sender.
                    notification.setContentTitle(from);
                    // For a single new conversation, the ticker is based on the sender's name.
                    notificationTicker = from;
                }

                // The notification content will be the subject of the conversation.
                notification.setContentText(getSingleMessageLittleText(context, conversation.subject));

                // The notification subtext will be the subject of the conversation for inbox
                // notifications, or will based on the the label name for user label
                // notifications.
                notification.setSubText(isInbox ? notificationAccount : notificationLabelName);

                if (multipleUnseenThread) {
                    notification.setLargeIcon(getDefaultNotificationIcon(context, folder, true));
                }
                final NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(
                        notification);

                // Seek the message cursor to the first unread message
                final Message message;
                if (messageCursor.moveToPosition(firstUnseenMessagePos)) {
                    message = messageCursor.getMessage();
                    bigText.bigText(getSingleMessageBigText(context, conversation.subject, message));
                } else {
                    LogUtils.e(LOG_TAG, "Failed to load message");
                    message = null;
                }

                if (message != null) {
                    final Set<String> notificationActions = folderPreferences.getNotificationActions(account);

                    final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder);

                    NotificationActionUtils.addNotificationActions(context, notificationIntent, notification,
                            account, conversation, message, folder, notificationId, when, notificationActions);
                }
            } else {
                // For an old-style notification

                // The title of a single conversation notification is built from both the sender
                // and subject of the new message.
                notification.setContentTitle(
                        getSingleMessageNotificationTitle(context, from, conversation.subject));

                // The notification content will be the subject of the conversation for inbox
                // notifications, or will based on the the label name for user label
                // notifications.
                notification.setContentText(isInbox ? notificationAccount : notificationLabelName);

                // For a single new conversation, the ticker is based on the sender's name.
                notificationTicker = from;
            }
        } finally {
            if (messageCursor != null) {
                messageCursor.close();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    // Build the notification ticker
    if (notificationLabelName != null && notificationTicker != null) {
        // This is a per label notification, format the ticker with that information
        notificationTicker = res.getString(R.string.label_notification_ticker, notificationLabelName,
                notificationTicker);
    }

    if (notificationTicker != null) {
        // If we didn't generate a notification ticker, it will default to account name
        notification.setTicker(notificationTicker);
    }

    // Set the number in the notification
    if (unreadCount > 1) {
        notification.setNumber(unreadCount);
    }

    notification.setContentIntent(clickIntent);
}

From source file:lewa.support.v7.widget.SearchView.java

private CharSequence getDecoratedHint(CharSequence hintText) {
    // If the field is always expanded, then don't add the search icon to the hint
    if (!mIconifiedByDefault)
        return hintText;

    SpannableStringBuilder ssb = new SpannableStringBuilder("   "); // for the icon
    ssb.append(hintText);// ww w .  ja v a2s  . co  m
    Drawable searchIcon = getContext().getResources().getDrawable(mSearchIconResId);
    int textSize = (int) (mQueryTextView.getTextSize() * 1.25);
    searchIcon.setBounds(0, 0, textSize, textSize);
    ssb.setSpan(new ImageSpan(searchIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ssb;
}

From source file:eu.faircode.netguard.ActivitySettings.java

private void markPro(Preference pref, String sku) {
    if (sku == null || !IAB.isPurchased(sku, this)) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        boolean dark = prefs.getBoolean("dark_theme", false);
        SpannableStringBuilder ssb = new SpannableStringBuilder("  " + pref.getTitle());
        ssb.setSpan(/*from w  w  w .  j av  a2  s.com*/
                new ImageSpan(this,
                        dark ? R.drawable.ic_shopping_cart_white_24dp : R.drawable.ic_shopping_cart_black_24dp),
                0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        pref.setTitle(ssb);
    }
}

From source file:android.support.v7.widget.SearchView.java

private CharSequence getDecoratedHint(CharSequence hintText) {
    // If the field is always expanded or we don't have a search hint icon,
    // then don't add the search icon to the hint.
    if (!mIconifiedByDefault || mSearchHintIcon == null) {
        return hintText;
    }/*w w w. j  av a2  s.com*/

    final int textSize = (int) (mSearchSrcTextView.getTextSize() * 1.25);
    mSearchHintIcon.setBounds(0, 0, textSize, textSize);

    final SpannableStringBuilder ssb = new SpannableStringBuilder("   ");
    ssb.setSpan(new ImageSpan(mSearchHintIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.append(hintText);
    return ssb;
}

From source file:kr.wdream.storyshop.AndroidUtilities.java

public static SpannableStringBuilder replaceTags(String str, int flag) {
    try {/*  w w w . j  a  v  a 2s .  co  m*/
        int start;
        int end;
        StringBuilder stringBuilder = new StringBuilder(str);
        if ((flag & FLAG_TAG_BR) != 0) {
            while ((start = stringBuilder.indexOf("<br>")) != -1) {
                stringBuilder.replace(start, start + 4, "\n");
            }
            while ((start = stringBuilder.indexOf("<br/>")) != -1) {
                stringBuilder.replace(start, start + 5, "\n");
            }
        }
        ArrayList<Integer> bolds = new ArrayList<>();
        if ((flag & FLAG_TAG_BOLD) != 0) {
            while ((start = stringBuilder.indexOf("<b>")) != -1) {
                stringBuilder.replace(start, start + 3, "");
                end = stringBuilder.indexOf("</b>");
                if (end == -1) {
                    end = stringBuilder.indexOf("<b>");
                }
                stringBuilder.replace(end, end + 4, "");
                bolds.add(start);
                bolds.add(end);
            }
        }
        ArrayList<Integer> colors = new ArrayList<>();
        if ((flag & FLAG_TAG_COLOR) != 0) {
            while ((start = stringBuilder.indexOf("<c#")) != -1) {
                stringBuilder.replace(start, start + 2, "");
                end = stringBuilder.indexOf(">", start);
                int color = Color.parseColor(stringBuilder.substring(start, end));
                stringBuilder.replace(start, end + 1, "");
                end = stringBuilder.indexOf("</c>");
                stringBuilder.replace(end, end + 4, "");
                colors.add(start);
                colors.add(end);
                colors.add(color);
            }
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
        for (int a = 0; a < bolds.size() / 2; a++) {
            spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                    bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        for (int a = 0; a < colors.size() / 3; a++) {
            spannableStringBuilder.setSpan(new ForegroundColorSpan(colors.get(a * 3 + 2)), colors.get(a * 3),
                    colors.get(a * 3 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableStringBuilder;
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    return new SpannableStringBuilder(str);
}

From source file:cm.aptoide.com.actionbarsherlock.widget.SearchView.java

private CharSequence getDecoratedHint(CharSequence hintText) {
    // If the field is always expanded, then don't add the search icon to the hint
    if (!mIconifiedByDefault)
        return hintText;

    SpannableStringBuilder ssb = new SpannableStringBuilder("   "); // for the icon
    ssb.append(hintText);/*from www .  j a  va 2 s  . c o  m*/
    Drawable searchIcon = getContext().getResources().getDrawable(getSearchIconId());
    int textSize = (int) (mQueryTextView.getTextSize() * 1.25);
    searchIcon.setBounds(0, 0, textSize, textSize);
    ssb.setSpan(new ImageSpan(searchIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ssb;
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static SpannableStringBuilder replaceTags(String str, int flag) {
    try {/* ww w. j a v a  2  s  .c o  m*/
        int start;
        int end;
        StringBuilder stringBuilder = new StringBuilder(str);
        if ((flag & FLAG_TAG_BR) != 0) {
            while ((start = stringBuilder.indexOf("<br>")) != -1) {
                stringBuilder.replace(start, start + 4, "\n");
            }
            while ((start = stringBuilder.indexOf("<br/>")) != -1) {
                stringBuilder.replace(start, start + 5, "\n");
            }
        }
        ArrayList<Integer> bolds = new ArrayList<>();
        if ((flag & FLAG_TAG_BOLD) != 0) {
            while ((start = stringBuilder.indexOf("<b>")) != -1) {
                stringBuilder.replace(start, start + 3, "");
                end = stringBuilder.indexOf("</b>");
                if (end == -1) {
                    end = stringBuilder.indexOf("<b>");
                }
                stringBuilder.replace(end, end + 4, "");
                bolds.add(start);
                bolds.add(end);
            }
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
        for (int a = 0; a < bolds.size() / 2; a++) {
            spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                    bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableStringBuilder;
    } catch (Exception e) {
        FileLog.e(e);
    }
    return new SpannableStringBuilder(str);
}