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.securecomcode.text.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;//from  w  w  w . j a  v a2  s.  c om
    }

    List<NotificationItem> notifications = notificationState.getNotifications();
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    Recipient recipient = notifications.get(0).getIndividualRecipient();

    builder.setSmallIcon(R.drawable.icon_notification);
    builder.setLargeIcon(recipient.getContactPhoto());
    builder.setContentTitle(recipient.toShortString());
    builder.setContentText(notifications.get(0).getText());
    builder.setContentIntent(notifications.get(0).getPendingIntent(context));
    builder.setContentInfo(String.valueOf(notificationState.getMessageCount()));
    builder.setNumber(notificationState.getMessageCount());

    if (masterSecret != null) {
        builder.addAction(R.drawable.check, context.getString(R.string.MessageNotifier_mark_as_read),
                notificationState.getMarkAsReadIntent(context, masterSecret));
    }

    SpannableStringBuilder content = new SpannableStringBuilder();

    for (NotificationItem item : notifications) {
        content.append(item.getBigStyleSummary());
        content.append('\n');
    }

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

    setNotificationAlarms(context, builder, signal);

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

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

From source file:com.yelinaung.karrency.app.ui.ExchangeRateFragment.java

private void showAbout() {
    PackageManager pm = mContext.getPackageManager();
    String packageName = mContext.getPackageName();
    String versionName;//  w w  w .j av a2s . c om
    try {
        assert pm != null;
        PackageInfo info = pm.getPackageInfo(packageName, 0);
        versionName = info.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        versionName = "";
    }
    AlertDialog.Builder b = new AlertDialog.Builder(rootView.getRootView().getContext())
            .setTitle(R.string.about).setMessage(new SpannableStringBuilder()
                    .append(Html.fromHtml(getString(R.string.about_body, versionName))));
    b.create().show();
}

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

public static SpannableStringBuilder createMessageInfo(Context context, Conversation conv,
        final boolean resourceCachingRequired) {
    SpannableStringBuilder messageInfo = new SpannableStringBuilder();

    try {//  w  w  w  . j  a  v  a 2s . co  m
        ConversationInfo conversationInfo = conv.conversationInfo;
        int sendingStatus = conv.sendingState;
        boolean hasSenders = false;
        // This covers the case where the sender is "me" and this is a draft
        // message, which means this will only run once most of the time.
        for (ParticipantInfo p : conversationInfo.participantInfos) {
            if (!TextUtils.isEmpty(p.name)) {
                hasSenders = true;
                break;
            }
        }
        getSenderResources(context, resourceCachingRequired);
        int count = conversationInfo.messageCount;
        int draftCount = conversationInfo.draftCount;
        if (count > 1) {
            messageInfo.append(count + "");
        }
        messageInfo.setSpan(
                CharacterStyle.wrap(conv.read ? sMessageInfoReadStyleSpan : sMessageInfoUnreadStyleSpan), 0,
                messageInfo.length(), 0);
        if (draftCount > 0) {
            // If we are showing a message count or any draft text and there
            // is at least 1 sender, prepend the sending state text with a
            // comma.
            if (hasSenders || count > 1) {
                messageInfo.append(sSendersSplitToken);
            }
            SpannableStringBuilder draftString = new SpannableStringBuilder();
            if (draftCount == 1) {
                draftString.append(sDraftSingularString);
            } else {
                draftString.append(sDraftPluralString)
                        .append(String.format(sDraftCountFormatString, draftCount));
            }
            draftString.setSpan(CharacterStyle.wrap(sDraftsStyleSpan), 0, draftString.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            messageInfo.append(draftString);
        }
        // TS: chao.zhang 2015-09-29 EMAIL FEATURE-585337 MOD_S
        //NOTE:currently,we DONOT show the status in senderView, with our ERGO,show the status on the side if Subject.diable it!!!
        //boolean showState = sendingStatus == UIProvider.ConversationSendingState.SENDING ||
        //        sendingStatus == UIProvider.ConversationSendingState.RETRYING ||
        //       sendingStatus == UIProvider.ConversationSendingState.SEND_ERROR;
        boolean showState = false;
        // TS: chao.zhang 2015-09-29 EMAIL FEATURE-585337 MOD_E
        if (showState) {
            // If we are showing a message count or any draft text, prepend
            // the sending state text with a comma.
            if (count > 1 || draftCount > 0) {
                messageInfo.append(sSendersSplitToken);
            }

            SpannableStringBuilder stateSpan = new SpannableStringBuilder();

            if (sendingStatus == UIProvider.ConversationSendingState.SENDING) {
                stateSpan.append(sSendingString);
                stateSpan.setSpan(sSendingStyleSpan, 0, stateSpan.length(), 0);
            } else if (sendingStatus == UIProvider.ConversationSendingState.RETRYING) {
                stateSpan.append(sQueuedString);
                stateSpan.setSpan(sQueuedStyleSpan, 0, stateSpan.length(), 0);
            } else if (sendingStatus == UIProvider.ConversationSendingState.SEND_ERROR) {
                stateSpan.append(sFailedString);
                stateSpan.setSpan(sFailedStyleSpan, 0, stateSpan.length(), 0);
            }
            messageInfo.append(stateSpan);
        }

        // Prepend a space if we are showing other message info text.
        if (count > 1 || (draftCount > 0 && hasSenders) || showState) {
            messageInfo.insert(0, sMessageCountSpacerString);
        }
    } finally {
        if (!resourceCachingRequired) {
            clearResourceCache();
        }
    }

    return messageInfo;
}

From source file:com.murrayc.galaxyzoo.app.ZooFragment.java

private void showAbout() {
    final Activity activity = getActivity();
    final AlertDialog.Builder builder = new AlertDialog.Builder(activity);

    // Get the layout inflater
    final LayoutInflater inflater = activity.getLayoutInflater();

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    final View view = inflater.inflate(R.layout.about, null);
    builder.setView(view);/*from  w w w.j  av a 2  s.c o m*/

    final TextView textView = (TextView) view.findViewById(R.id.textViewAbout);
    if (textView == null) {
        Log.error("showAbout: textView was null.");
        return;
    }

    //This voodoo makes the textviews' HTML links clickable:
    //See http://stackoverflow.com/questions/2734270/how-do-i-make-links-in-a-textview-clickable/20647011#20647011
    textView.setMovementMethod(LinkMovementMethod.getInstance());

    final String versionText = String.format(getString(R.string.about_version_text_format),
            BuildConfig.VERSION_NAME);

    //The about dialog's text is split into multiple strings to make translation easier,
    //so we need to concatenate them here.
    //Note that we use getText(), not getString(),
    //so we don't lose the <a href=""> links.
    //Likewise, we use SpannableStringBuilder instead of StringBuilder,
    //because we lose the links when using StringBuilder.
    final SpannableStringBuilder strBuilder = new SpannableStringBuilder();
    final String PARAGRAPH_BREAK = "\n\n";
    strBuilder.append(versionText);
    strBuilder.append(PARAGRAPH_BREAK);
    strBuilder.append(getText(R.string.about_text1));
    strBuilder.append(PARAGRAPH_BREAK);
    strBuilder.append(getText(R.string.about_text2));
    strBuilder.append(PARAGRAPH_BREAK);
    strBuilder.append(getText(R.string.about_text3));
    strBuilder.append(PARAGRAPH_BREAK);
    strBuilder.append(getText(R.string.about_text3b));
    strBuilder.append(PARAGRAPH_BREAK);
    strBuilder.append(getText(R.string.about_text4));
    strBuilder.append(PARAGRAPH_BREAK);
    strBuilder.append(getText(R.string.about_text5));
    strBuilder.append(PARAGRAPH_BREAK);
    strBuilder.append(getText(R.string.about_text6));

    textView.setText(strBuilder);

    /* We used to put the version text into a separate TextView,
       but when the about text in textView is too long,
       the scroll never reaches this far.
       It does work when we add it to first regular textView.
     */
    /*
    final TextView textViewVersion = (TextView) view.findViewById(R.id.textViewVersion);
    if (textViewVersion != null) {
    textViewVersion.setText(versionText);
    }
    */

    final AlertDialog dialog = builder.create();
    dialog.setTitle(R.string.app_name);
    dialog.setIcon(R.mipmap.ic_launcher);

    dialog.show();
}

From source file:com.ubercab.client.feature.notification.handler.TripNotificationHandler.java

private NotificationCompat.InboxStyle buildStyleInbox(NotificationCompat.Builder paramBuilder,
          TripNotificationData paramTripNotificationData, String paramString) {
      NotificationCompat.InboxStyle localInboxStyle = new NotificationCompat.InboxStyle(paramBuilder)
              .setSummaryText(paramString);
      Iterator localIterator = paramTripNotificationData.getFareSplitClients().iterator();
      while (localIterator.hasNext()) {
          TripNotificationData.FareSplitClient localFareSplitClient = (TripNotificationData.FareSplitClient) localIterator
                  .next();/*from w ww  .ja  v a  2  s . co  m*/
          SpannableString localSpannableString = new SpannableString(localFareSplitClient.getName());
          localSpannableString.setSpan(new StyleSpan(1), 0, localSpannableString.length(), 33);
          SpannableStringBuilder localSpannableStringBuilder = new SpannableStringBuilder();
          localSpannableStringBuilder.append(localSpannableString);
          localSpannableStringBuilder.append(" ");
          localSpannableStringBuilder.append(localFareSplitClient.getDisplayStatus(getContext()));
          localInboxStyle.addLine(localSpannableStringBuilder);
      }
      return localInboxStyle;
  }

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

/**
 * Provides feedback for the specified utterance.
 *
 * @param queueMode The queueMode of the Utterance.
 * @param utterance The utterance to provide feedback for.
 *//*from   w w w. j ava 2s . c  o m*/
private void provideFeedbackForUtterance(int queueMode, Utterance utterance) {
    final Bundle metadata = utterance.getMetadata();
    final float earconRate = metadata.getFloat(Utterance.KEY_METADATA_EARCON_RATE, 1.0f);
    final float earconVolume = metadata.getFloat(Utterance.KEY_METADATA_EARCON_VOLUME, 1.0f);
    final Bundle nonSpeechMetadata = new Bundle();
    nonSpeechMetadata.putFloat(Utterance.KEY_METADATA_EARCON_RATE, earconRate);
    nonSpeechMetadata.putFloat(Utterance.KEY_METADATA_EARCON_VOLUME, earconVolume);

    // Perform cleanup of spoken text for each separate part of the utterance, e.g. we do not
    // want to combine repeated characters if they span different parts, and we still want to
    // expand single-character symbols if a certain part is a single character.
    final SpannableStringBuilder textToSpeak = new SpannableStringBuilder();
    for (CharSequence text : utterance.getSpoken()) {
        if (!TextUtils.isEmpty(text)) {
            CharSequence processedText = SpeechCleanupUtils.collapseRepeatedCharactersAndCleanUp(mContext,
                    text);
            StringBuilderUtils.appendWithSeparator(textToSpeak, processedText);
        }
    }

    // Get speech settings from utterance.
    final int flags = metadata.getInt(Utterance.KEY_METADATA_SPEECH_FLAGS, 0);
    final Bundle speechMetadata = metadata.getBundle(Utterance.KEY_METADATA_SPEECH_PARAMS);

    final int utteranceGroup = utterance.getMetadata().getInt(Utterance.KEY_UTTERANCE_GROUP,
            SpeechController.UTTERANCE_GROUP_DEFAULT);

    mSpeechController.speak(textToSpeak, utterance.getAuditory(), utterance.getHaptic(), queueMode, flags,
            utteranceGroup, speechMetadata, nonSpeechMetadata);
}

From source file:com.google.android.apps.location.gps.gnsslogger.PlotFragment.java

/**
 *  Updates the CN0 versus Time plot data from a {@link GnssMeasurement}
 *//*from   w ww  .  j  a  v  a 2s  . c  om*/
protected void updateCnoTab(GnssMeasurementsEvent event) {
    long timeInSeconds = TimeUnit.NANOSECONDS.toSeconds(event.getClock().getTimeNanos());
    if (mInitialTimeSeconds < 0) {
        mInitialTimeSeconds = timeInSeconds;
    }

    // Building the texts message in analysis text view
    List<GnssMeasurement> measurements = sortByCarrierToNoiseRatio(new ArrayList<>(event.getMeasurements()));
    SpannableStringBuilder builder = new SpannableStringBuilder();
    double currentAverage = 0;
    if (measurements.size() >= NUMBER_OF_STRONGEST_SATELLITES) {
        mAverageCn0 = (mAverageCn0 * mMeasurementCount
                + (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz()
                        + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz())
                        / NUMBER_OF_STRONGEST_SATELLITES)
                / (++mMeasurementCount);
        currentAverage = (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz()
                + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz())
                / NUMBER_OF_STRONGEST_SATELLITES;
    }
    builder.append(getString(R.string.history_average_hint, sDataFormat.format(mAverageCn0) + "\n"));
    builder.append(getString(R.string.current_average_hint, sDataFormat.format(currentAverage) + "\n"));
    for (int i = 0; i < NUMBER_OF_STRONGEST_SATELLITES && i < measurements.size(); i++) {
        int start = builder.length();
        builder.append(mDataSetManager.getConstellationPrefix(measurements.get(i).getConstellationType())
                + measurements.get(i).getSvid() + ": " + sDataFormat.format(measurements.get(i).getCn0DbHz())
                + "\n");
        int end = builder.length();
        builder.setSpan(
                new ForegroundColorSpan(mColorMap.getColor(measurements.get(i).getSvid(),
                        measurements.get(i).getConstellationType())),
                start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    builder.append(getString(R.string.satellite_number_sum_hint, measurements.size()));
    mAnalysisView.setText(builder);

    // Adding incoming data into Dataset
    mLastTimeReceivedSeconds = timeInSeconds - mInitialTimeSeconds;
    for (GnssMeasurement measurement : measurements) {
        int constellationType = measurement.getConstellationType();
        int svID = measurement.getSvid();
        if (constellationType != GnssStatus.CONSTELLATION_UNKNOWN) {
            mDataSetManager.addValue(CN0_TAB, constellationType, svID, mLastTimeReceivedSeconds,
                    measurement.getCn0DbHz());
        }
    }

    mDataSetManager.fillInDiscontinuity(CN0_TAB, mLastTimeReceivedSeconds);

    // Checks if the plot has reached the end of frame and resize
    if (mLastTimeReceivedSeconds > mCurrentRenderer.getXAxisMax()) {
        mCurrentRenderer.setXAxisMax(mLastTimeReceivedSeconds);
        mCurrentRenderer.setXAxisMin(mLastTimeReceivedSeconds - TIME_INTERVAL_SECONDS);
    }

    mChartView.invalidate();
}

From source file:com.juick.android.TagsFragment.java

private void reloadTags(final View view) {
    final View selectedContainer = myView.findViewById(R.id.selected_container);
    final View progressAll = myView.findViewById(R.id.progress_all);
    Thread thr = new Thread(new Runnable() {

        public void run() {
            Bundle args = getArguments();
            MicroBlog microBlog;//from   w w  w . j a v  a  2  s  .  c  om
            JSONArray json = null;
            final int tagsUID = showMine ? uid : 0;
            if (PointMessageID.CODE.equals(args.getString("microblog"))) {
                microBlog = MainActivity.microBlogs.get(PointMessageID.CODE);
                json = ((PointMicroBlog) microBlog).getUserTags(view, uidS);
            } else {
                microBlog = MainActivity.microBlogs.get(JuickMessageID.CODE);
                json = ((JuickMicroBlog) microBlog).getUserTags(view, tagsUID);
            }
            if (isAdded()) {
                final SpannableStringBuilder tagsSSB = new SpannableStringBuilder();
                if (json != null) {
                    try {
                        int cnt = json.length();
                        ArrayList<TagSort> sortables = new ArrayList<TagSort>();
                        for (int i = 0; i < cnt; i++) {
                            final String tagg = json.getJSONObject(i).getString("tag");
                            final int messages = json.getJSONObject(i).getInt("messages");
                            sortables.add(new TagSort(tagg, messages));
                        }
                        Collections.sort(sortables);
                        HashMap<String, Double> scales = new HashMap<String, Double>();
                        for (int sz = 0, sortablesSize = sortables.size(); sz < sortablesSize; sz++) {
                            TagSort sortable = sortables.get(sz);
                            if (sz < 10) {
                                scales.put(sortable.tag, 2.0);
                            } else if (sz < 20) {
                                scales.put(sortable.tag, 1.5);
                            }
                        }
                        int start = 0;
                        if (microBlog instanceof JuickMicroBlog
                                && getArguments().containsKey("add_system_tags")) {
                            start = -4;
                        }
                        for (int i = start; i < cnt; i++) {
                            final String tagg;
                            switch (i) {
                            case -4:
                                tagg = "public";
                                break;
                            case -3:
                                tagg = "friends";
                                break;
                            case -2:
                                tagg = "notwitter";
                                break;
                            case -1:
                                tagg = "readonly";
                                break;
                            default:
                                tagg = json.getJSONObject(i).getString("tag");
                                break;

                            }
                            int index = tagsSSB.length();
                            tagsSSB.append("*" + tagg);
                            tagsSSB.setSpan(new URLSpan(tagg) {
                                @Override
                                public void onClick(View widget) {
                                    onTagClick(tagg, tagsUID);
                                }
                            }, index, tagsSSB.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            Double scale = scales.get(tagg);
                            if (scale != null) {
                                tagsSSB.setSpan(new RelativeSizeSpan((float) scale.doubleValue()), index,
                                        tagsSSB.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                            tagOffsets.put(tagg, new TagOffsets(index, tagsSSB.length()));
                            tagsSSB.append(" ");

                        }
                    } catch (Exception ex) {
                        tagsSSB.append("Error: " + ex.toString());
                    }
                }
                if (getActivity() != null) {
                    // maybe already closed?
                    getActivity().runOnUiThread(new Runnable() {

                        public void run() {
                            TextView tv = (TextView) myView.findViewById(R.id.tags);
                            progressAll.setVisibility(View.GONE);
                            if (multi)
                                selectedContainer.setVisibility(View.VISIBLE);
                            tv.setText(tagsSSB, TextView.BufferType.SPANNABLE);
                            tv.setMovementMethod(LinkMovementMethod.getInstance());
                            MainActivity.restyleChildrenOrWidget(view);
                            final TextView selected = (TextView) myView.findViewById(R.id.selected);
                            selected.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }
        }
    });
    thr.start();
}

From source file:com.roamprocess1.roaming4world.ui.messages.ConversationsAdapter.java

private CharSequence formatMessage(Cursor cursor) {
    SpannableStringBuilder buf = new SpannableStringBuilder();
    String remoteContactFull = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM_FULL));
    CallerInfo callerInfo = CallerInfo.getCallerInfoFromSipUri(mContext, remoteContactFull);

    System.out.println("remoteContactFull:" + remoteContactFull);

    if (callerInfo != null && callerInfo.contactExists) {
        buf.append(callerInfo.name);/*  w  w w .  j  av  a2  s.  com*/
    } else {
        buf.append(SipUri.getDisplayedSimpleContact(remoteContactFull));
    }

    int counter = cursor.getInt(cursor.getColumnIndex("counter"));

    if (counter > 1) {
        buf.append(" (" + counter + ") ");
    }

    int read = cursor.getInt(cursor.getColumnIndex(SipMessage.FIELD_READ));
    // Unread messages are shown in bold
    if (read == 0) {
        buf.setSpan(STYLE_BOLD, 0, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    System.out.println("return:" + buf);
    return buf;
}

From source file:com.google.android.apps.iosched.util.UIUtils.java

public static void updateTimeAndLivestreamBlockUI(final Context context, long blockStart, long blockEnd,
        boolean hasLivestream, View backgroundView, TextView titleView, TextView subtitleView,
        CharSequence subtitle) {//from  ww  w .ja  va  2  s  .com
    long currentTimeMillis = getCurrentTime(context);

    boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < CONFERENCE_END_MILLIS);
    boolean present = (blockStart <= currentTimeMillis && currentTimeMillis <= blockEnd);

    final Resources res = context.getResources();
    if (backgroundView != null) {
        backgroundView.setBackgroundColor(past ? res.getColor(R.color.past_background_color) : 0);
    }

    if (titleView != null) {
        titleView.setTypeface(Typeface.SANS_SERIF, past ? Typeface.NORMAL : Typeface.BOLD);
    }

    if (subtitleView != null) {
        boolean empty = true;
        SpannableStringBuilder sb = new SpannableStringBuilder(); // TODO: recycle
        if (subtitle != null) {
            sb.append(subtitle);
            empty = false;
        }

        if (present) {
            if (sNowPlayingText == null) {
                sNowPlayingText = Html.fromHtml(context.getString(R.string.now_playing_badge));
            }
            if (!empty) {
                sb.append("  ");
            }
            sb.append(sNowPlayingText);

            if (hasLivestream) {
                if (sLivestreamNowText == null) {
                    sLivestreamNowText = Html
                            .fromHtml("&nbsp;&nbsp;" + context.getString(R.string.live_now_badge));
                }
                sb.append(sLivestreamNowText);
            }
        } else if (hasLivestream) {
            if (sLivestreamAvailableText == null) {
                sLivestreamAvailableText = Html.fromHtml(context.getString(R.string.live_available_badge));
            }
            if (!empty) {
                sb.append("  ");
            }
            sb.append(sLivestreamAvailableText);
        }

        subtitleView.setText(sb);
    }
}