Example usage for android.text SpannableStringBuilder SpannableStringBuilder

List of usage examples for android.text SpannableStringBuilder SpannableStringBuilder

Introduction

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

Prototype

public SpannableStringBuilder() 

Source Link

Document

Create a new SpannableStringBuilder with empty contents

Usage

From source file:com.amazon.android.ui.widget.EllipsizedTextView.java

/**
 * Sets ellipsis properties./* www  .ja  va 2 s  . c o  m*/
 *
 * @param widthMeasureSpec  Ellipsis width.
 * @param heightMeasureSpec Ellipsis height.
 * @param layout            Layout for ellipsis.
 * @param lastLine          Last line length for ellipsis.
 * @param maxLines          Max lines in ellipsis.
 */
private void setEllipsis(int widthMeasureSpec, int heightMeasureSpec, Layout layout, int lastLine,
        int maxLines) {

    mIsEllipsized = true;
    setFocusable(true);
    setClickable(true);
    final SpannableString ss = new SpannableString(mCharSequence);
    String visibleText = mCharSequence.toString();

    mEllipsisImage = new StateImageSpan(getContext(), mGuillemetDrawableId, ImageSpan.ALIGN_BASELINE);

    final SpannableStringBuilder spannedText = new SpannableStringBuilder();
    int ellipsisIndex = layout.getLineStart(Math.min(lastLine + 1, maxLines));

    // Keep chopping words off until the ellipsis is on a visible line or there is only one
    // line left.
    do {
        // Only truncate the last line for long description.
        if (lastLine >= maxLines) {
            // Getting the first word break index before the last index of maxline.
            int safeBreakIndex = breakBefore(visibleText, ellipsisIndex, BreakIterator.getWordInstance());
            final int maxLineStart = layout.getLineStart(maxLines - 1);

            // If this check pass, it means we just truncated a word that is longer than a line.
            if (safeBreakIndex < maxLineStart) {
                // Need to check character by character and break in the middle now. Checking
                // word by word should cover most cases, only do this if a word is longer than
                // line width.
                safeBreakIndex = breakBefore(visibleText, ellipsisIndex, BreakIterator.getCharacterInstance());
            }
            ellipsisIndex = safeBreakIndex;
        }

        visibleText = visibleText.substring(0, ellipsisIndex);
        final CharSequence charOutput = ss.subSequence(0, ellipsisIndex);

        // Re-add ellipsis and convert to image
        spannedText.replace(0, spannedText.length(), charOutput);
        spannedText.append(ELLIPSIS);

        spannedText.setSpan(mEllipsisImage, ellipsisIndex, ellipsisIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

        // Reset text and re-measure.
        super.setText(spannedText, BufferType.SPANNABLE);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    } while (getLineCount() > getMaxLines() && getLineCount() > 1);
    requestFocus();
}

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

private static void sendSingleThreadNotification(Context context, MasterSecret masterSecret,
        NotificationState notificationState, boolean signal) {
    if (notificationState.getNotifications().isEmpty()) {
        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID);
        return;//  w  w  w .  j  a va2  s . co m
    }

    List<NotificationItem> notifications = notificationState.getNotifications();
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    Recipient recipient = notifications.get(0).getIndividualRecipient();
    Drawable recipientPhoto = recipient.getContactPhoto();
    int largeIconTargetSize = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size);

    if (recipientPhoto != null) {
        Bitmap recipientPhotoBitmap = BitmapUtil.createFromDrawable(recipientPhoto, largeIconTargetSize,
                largeIconTargetSize);
        if (recipientPhotoBitmap != null)
            builder.setLargeIcon(recipientPhotoBitmap);
    }

    builder.setSmallIcon(R.drawable.icon_notification);
    builder.setColor(context.getResources().getColor(R.color.textsecure_primary));
    builder.setContentTitle(recipient.toShortString());
    builder.setContentText(notifications.get(0).getText());
    builder.setContentIntent(notifications.get(0).getPendingIntent(context));
    builder.setContentInfo(String.valueOf(notificationState.getMessageCount()));
    builder.setPriority(NotificationCompat.PRIORITY_HIGH);
    builder.setNumber(notificationState.getMessageCount());
    builder.setCategory(NotificationCompat.CATEGORY_MESSAGE);
    builder.setDeleteIntent(
            PendingIntent.getBroadcast(context, 0, new Intent(DeleteReceiver.DELETE_REMINDER_ACTION), 0));
    if (recipient.getContactUri() != null)
        builder.addPerson(recipient.getContactUri().toString());

    long timestamp = notifications.get(0).getTimestamp();
    if (timestamp != 0)
        builder.setWhen(timestamp);

    if (masterSecret != null) {
        Action markAsReadAction = new Action(R.drawable.check,
                context.getString(R.string.MessageNotifier_mark_as_read),
                notificationState.getMarkAsReadIntent(context, masterSecret));
        builder.addAction(markAsReadAction);
        builder.extend(new NotificationCompat.WearableExtender().addAction(markAsReadAction));
    }

    SpannableStringBuilder content = new SpannableStringBuilder();

    ListIterator<NotificationItem> iterator = notifications.listIterator(notifications.size());
    while (iterator.hasPrevious()) {
        NotificationItem item = iterator.previous();
        content.append(item.getBigStyleSummary());
        content.append('\n');
    }

    builder.setStyle(new BigTextStyle().bigText(content));

    setNotificationAlarms(context, builder, signal, notificationState.getRingtone(),
            notificationState.getVibrate());

    if (signal) {
        builder.setTicker(notifications.get(0).getTickerText());
    }

    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID,
            builder.build());
}

From source file:com.yangtsaosoftware.pebblemessenger.activities.SetupFragment.java

private void test_pebble_app(Context context) {
    BroadcastReceiver br = new BroadcastReceiver() {
        @Override/*from   w ww .j  ava2 s. c om*/
        public void onReceive(Context context, Intent intent) {

            byte[] command = intent.getByteArrayExtra(Constants.BROADCAST_VERSION);
            boolean result = true;
            if (command == null || command[0] < Constants.PEBBLE_VERSION[0]) {
                result = false;
            } else if (command[1] < Constants.PEBBLE_VERSION[1]) {
                result = false;
            } else if (command[2] < Constants.PEBBLE_VERSION[2]) {
                result = false;
            }
            SpannableStringBuilder ssb = new SpannableStringBuilder();
            ssb.append(textInfo.getText());
            ssb.append(context.getString(R.string.setup_app_test));
            ssb.append('\n');
            ssb.append(context.getString(R.string.setup_install_pebble_app));
            ssb.append((result ? greenText(R.string.setup_check_ok) : redText(R.string.setup_check_bad)));
            ssb.append('\n');
            textInfo.setText(ssb);
            svMyview.fullScroll(View.FOCUS_DOWN);
            LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
        }
    };
    IntentFilter intentFilter = new IntentFilter(SetupFragment.class.getName());
    LocalBroadcastManager.getInstance(context).registerReceiver(br, intentFilter);
    Intent inner_intent = new Intent(PebbleCenter.class.getName());
    inner_intent.putExtra(Constants.BROADCAST_COMMAND, Constants.BROADCAST_PEBBLE_TEST);
    LocalBroadcastManager.getInstance(context).sendBroadcast(inner_intent);
}

From source file:es.usc.citius.servando.calendula.activities.ReminderNotification.java

private static void styleForRoutine(Context ctx, NotificationCompat.InboxStyle style, Routine r,
        List<ScheduleItem> doses) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);

    for (ScheduleItem scheduleItem : doses) {
        //TODO: Use DecimalFormat
        // DecimalFormat timeFormatter = new DecimalFormat("#");
        //String dfDose = timeFormatter.format(scheduleItem.dose());

        final SpannableStringBuilder SpItem = new SpannableStringBuilder();
        final Medicine med = scheduleItem.schedule().medicine();
        SpItem.append(med.name());//from www  .  j  ava  2s. co  m
        SpItem.append(":  " + scheduleItem.dose() + " " + med.presentation().units(ctx.getResources()));
        style.addLine(SpItem);
    }
    String delayMinutesStr = prefs.getString("alarm_repeat_frequency", "15");
    int delayMinutes = (int) Long.parseLong(delayMinutesStr);

    if (delayMinutes > 0) {
        String repeatTime = DateTime.now().plusMinutes(delayMinutes).toString("HH:mm");
        style.setSummaryText(ctx.getResources().getString(R.string.notification_repeat_message, repeatTime));
    } else {
        style.setSummaryText(doses.size() + " meds to take at " + r.name());
    }

}

From source file:com.android.talkback.speechrules.NodeSpeechRuleProcessor.java

/**
 * If the supplied node has a label, replaces the builder text with a
 * version formatted with the label./*from   w  w  w.  ja va 2  s .c  o  m*/
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void formatTextWithLabel(AccessibilityNodeInfoCompat node, SpannableStringBuilder builder) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
        return;

    // TODO: add getLabeledBy to support lib
    AccessibilityNodeInfo info = (AccessibilityNodeInfo) node.getInfo();
    if (info == null)
        return;
    AccessibilityNodeInfo labeledBy = info.getLabeledBy();
    if (labeledBy == null)
        return;
    AccessibilityNodeInfoCompat labelNode = new AccessibilityNodeInfoCompat(labeledBy);

    final SpannableStringBuilder labelDescription = new SpannableStringBuilder();
    Set<AccessibilityNodeInfoCompat> visitedNodes = new HashSet<>();
    appendDescriptionForTree(labelNode, labelDescription, null, null, visitedNodes);
    AccessibilityNodeInfoUtils.recycleNodes(visitedNodes);
    if (TextUtils.isEmpty(labelDescription)) {
        return;
    }

    final String labeled = mContext.getString(R.string.template_labeled_item, builder, labelDescription);
    Spannable spannableLabeledText = StringBuilderUtils.createSpannableFromTextWithTemplate(labeled, builder);

    // Replace the text of the builder.
    builder.clear();
    builder.append(spannableLabeledText);
}

From source file:org.solovyev.android.calculator.widget.CalculatorWidget.java

private void updateEditorState(@Nonnull Context context, @Nonnull RemoteViews views, @Nonnull EditorState state,
        @Nonnull SimpleTheme theme) {/*ww w  .j a  v a2s  .  c  o  m*/
    final boolean unspan = App.getTheme().light != theme.light;

    final CharSequence text = state.text;
    final int selection = state.selection;
    if (selection < 0 || selection > text.length()) {
        views.setTextViewText(R.id.calculator_editor, unspan ? App.unspan(text) : text);
        return;
    }

    final SpannableStringBuilder result;
    // inject cursor
    if (unspan) {
        final CharSequence beforeCursor = text.subSequence(0, selection);
        final CharSequence afterCursor = text.subSequence(selection, text.length());

        result = new SpannableStringBuilder();
        result.append(App.unspan(beforeCursor));
        result.append(getCursorString(context));
        result.append(App.unspan(afterCursor));
    } else {
        result = new SpannableStringBuilder(text);
        result.insert(selection, getCursorString(context));
    }
    views.setTextViewText(R.id.calculator_editor, result);
}

From source file:com.android.talkback.eventprocessor.ProcessorScrollPosition.java

private CharSequence getDescriptionForPageEvent(AccessibilityEvent event, AccessibilityNodeInfo source) {
    final int fromIndex = (event.getFromIndex() + 1);
    final int itemCount = event.getItemCount();
    if ((fromIndex <= 0) || (itemCount <= 0)) {
        return null;
    }//from  www  . ja v  a2 s .  c o  m

    CharSequence pageTitle = getSelectedPageTitle(source);
    if (!TextUtils.isEmpty(pageTitle)) {
        CharSequence count = mContext.getString(R.string.template_viewpager_index_count_short, fromIndex,
                itemCount);

        SpannableStringBuilder output = new SpannableStringBuilder();
        StringBuilderUtils.appendWithSeparator(output, pageTitle, count);
        return output;
    }

    return mContext.getString(R.string.template_viewpager_index_count, fromIndex, itemCount);
}

From source file:com.groksolutions.grok.mobile.annotation.AnnotationListFragment.java

/**
 * Format annotation message body for list item display
 *
 * @param annotation The annotation to format
 *
 * @return The formatted annotation text suitable for use with {@link android.widget.TextView}
 *///w ww .java 2s. c o  m
SpannableStringBuilder formatAnnotationBody(Annotation annotation) {
    int pos;

    // Format text
    SpannableStringBuilder text = new SpannableStringBuilder();

    // <br/> My Message
    pos = text.length();
    text.append(annotation.getMessage());
    text.setSpan(new RelativeSizeSpan(1.0f), pos, text.length(), 0);
    text.setSpan(new StyleSpan(Typeface.NORMAL), pos, text.length(), 0);

    // Attach hidden annotation ID to the text.
    // This ID is used by the actions attached to the list
    text.setSpan(new android.text.Annotation("id", annotation.getId()), 0, text.length(), 0);

    return text;
}

From source file:tw.idv.gasolin.pycontw2012.ui.SessionDetailFragment.java

/**
 * Handle {@link SessionsQuery} {@link Cursor}.
 *///from w  w w  . j a  va  2s .  c  o  m
private void onSessionQueryComplete(Cursor cursor) {
    try {
        mSessionCursor = true;
        if (!cursor.moveToFirst()) {
            return;
        }

        // Format time block this session occupies
        final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START);
        final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END);
        final Locale locale = getResources().getConfiguration().locale;
        final String roomName = UIUtils.getBestLocaleString(locale, cursor.getString(SessionsQuery.ROOM_NAME),
                cursor.getString(SessionsQuery.ROOM_NAME_ZH_TW),
                cursor.getString(SessionsQuery.ROOM_NAME_ZH_CN));
        final String subtitle = UIUtils.formatSessionSubtitle(blockStart, blockEnd, roomName, getActivity());

        mTitleString = cursor.getString(SessionsQuery.TITLE);
        mTitle.setText(mTitleString);
        mSubtitle.setText(subtitle);

        mUrl = cursor.getString(SessionsQuery.URL);
        if (TextUtils.isEmpty(mUrl)) {
            mUrl = "";
        }

        mHashtag = cursor.getString(SessionsQuery.HASHTAG);
        mTagDisplay = (TextView) mRootView.findViewById(R.id.session_tags_button);
        if (!TextUtils.isEmpty(mHashtag)) {
            // Create the button text
            SpannableStringBuilder sb = new SpannableStringBuilder();
            sb.append(getString(R.string.tag_stream) + " ");
            int boldStart = sb.length();
            sb.append(getHashtagsString());
            sb.setSpan(sBoldSpan, boldStart, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            mTagDisplay.setText(sb);

            mTagDisplay.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), TagStreamActivity.class);
                    intent.putExtra(TagStreamFragment.EXTRA_QUERY, getHashtagsString());
                    startActivity(intent);
                }
            });
        } else {
            mTagDisplay.setVisibility(View.GONE);
        }

        mRoomId = cursor.getString(SessionsQuery.ROOM_ID);

        // Unregister around setting checked state to avoid triggering
        // listener since change isn't user generated.
        mStarred.setOnCheckedChangeListener(null);
        mStarred.setChecked(cursor.getInt(SessionsQuery.STARRED) != 0);
        mStarred.setOnCheckedChangeListener(this);

        final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT);
        if (!TextUtils.isEmpty(sessionAbstract)) {
            UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract);
            mAbstract.setVisibility(View.VISIBLE);
            mHasSummaryContent = true;
        } else {
            mAbstract.setVisibility(View.GONE);
        }

        // Show empty message when all data is loaded, and nothing to show
        if (mSpeakersCursor && !mHasSummaryContent) {
            mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
        }

        AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sessions/" + mTitleString);

        updateLinksTab(cursor);

    } finally {
        cursor.close();
    }
}

From source file:piuk.blockchain.android.util.WalletUtils.java

public static Editable formatAddress(final String address, final int groupSize, final int lineSize) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();

    final int len = address.length();
    for (int i = 0; i < len; i += groupSize) {
        final int end = i + groupSize;
        final String part = address.substring(i, end < len ? end : len);

        builder.append(part);// w ww.  j ava 2s. c o m
        builder.setSpan(new TypefaceSpan("monospace"), builder.length() - part.length(), builder.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (end < len) {
            final boolean endOfLine = end % lineSize == 0;
            builder.append(endOfLine ? "\n" : Constants.THIN_SPACE);
        }
    }

    return builder;
}