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.android.talkback.SpeechController.java

/**
 * Spells the text.//from  ww w  .  j  a v a 2 s .c  o m
 */
public boolean spellUtterance(CharSequence text) {
    if (TextUtils.isEmpty(text)) {
        return false;
    }

    final SpannableStringBuilder builder = new SpannableStringBuilder();

    for (int i = 0; i < text.length(); i++) {
        final String cleanedChar = SpeechCleanupUtils.getCleanValueFor(mService, text.charAt(i));

        StringBuilderUtils.appendWithSeparator(builder, cleanedChar);
    }

    speak(builder, null, null, QUEUE_MODE_FLUSH_ALL, UTTERANCE_GROUP_DEFAULT, FeedbackItem.FLAG_NO_HISTORY,
            null, null, null);
    return true;
}

From source file:com.andrewshu.android.reddit.threads.ThreadsListActivity.java

public static void fillThreadsListItemView(int position, View view, ThingInfo item, ListActivity activity,
        HttpClient client, RedditSettings settings,
        ThumbnailOnClickListenerFactory thumbnailOnClickListenerFactory) {

    Resources res = activity.getResources();

    TextView titleView = (TextView) view.findViewById(R.id.title);
    TextView votesView = (TextView) view.findViewById(R.id.votes);
    TextView numCommentsSubredditView = (TextView) view.findViewById(R.id.numCommentsSubreddit);
    TextView nsfwView = (TextView) view.findViewById(R.id.nsfw);
    //        TextView submissionTimeView = (TextView) view.findViewById(R.id.submissionTime);
    ImageView voteUpView = (ImageView) view.findViewById(R.id.vote_up_image);
    ImageView voteDownView = (ImageView) view.findViewById(R.id.vote_down_image);
    View thumbnailContainer = view.findViewById(R.id.thumbnail_view);
    FrameLayout thumbnailFrame = (FrameLayout) view.findViewById(R.id.thumbnail_frame);
    ImageView thumbnailImageView = (ImageView) view.findViewById(R.id.thumbnail);
    ProgressBar indeterminateProgressBar = (ProgressBar) view.findViewById(R.id.indeterminate_progress);

    // Set the title and domain using a SpannableStringBuilder
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String title = item.getTitle();
    if (title == null)
        title = "";
    SpannableString titleSS = new SpannableString(title);
    int titleLen = title.length();
    titleSS.setSpan(/*from  w  w w.ja v  a2  s.c  om*/
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Large)),
            0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    String domain = item.getDomain();
    if (domain == null)
        domain = "";
    int domainLen = domain.length();
    SpannableString domainSS = new SpannableString("(" + item.getDomain() + ")");
    domainSS.setSpan(
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Small)),
            0, domainLen + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (Util.isLightTheme(settings.getTheme())) {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.purple));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.blue));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_50)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.gray_50));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_75)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    builder.append(titleSS).append(" ").append(domainSS);
    titleView.setText(builder);

    votesView.setText("" + item.getScore());
    numCommentsSubredditView.setText(Util.showNumComments(item.getNum_comments()) + "  " + item.getSubreddit());

    if (item.isOver_18()) {
        nsfwView.setVisibility(View.VISIBLE);
    } else {
        nsfwView.setVisibility(View.GONE);
    }

    // Set the up and down arrow colors based on whether user likes
    if (settings.isLoggedIn()) {
        if (item.getLikes() == null) {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.gray_75));
        } else if (item.getLikes() == true) {
            voteUpView.setImageResource(R.drawable.vote_up_red);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.arrow_red));
        } else {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_blue);
            votesView.setTextColor(res.getColor(R.color.arrow_blue));
        }
    } else {
        voteUpView.setImageResource(R.drawable.vote_up_gray);
        voteDownView.setImageResource(R.drawable.vote_down_gray);
        votesView.setTextColor(res.getColor(R.color.gray_75));
    }

    // Thumbnails open links
    if (thumbnailContainer != null) {
        if (Common.shouldLoadThumbnails(activity, settings)) {
            thumbnailContainer.setVisibility(View.VISIBLE);

            if (item.getUrl() != null) {
                OnClickListener thumbnailOnClickListener = thumbnailOnClickListenerFactory
                        .getThumbnailOnClickListener(item, activity);
                if (thumbnailOnClickListener != null) {
                    thumbnailFrame.setOnClickListener(thumbnailOnClickListener);
                }
            }

            // Show thumbnail based on ThingInfo
            if ("default".equals(item.getThumbnail()) || "self".equals(item.getThumbnail())
                    || StringUtils.isEmpty(item.getThumbnail())) {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                thumbnailImageView.setImageResource(R.drawable.go_arrow);
            } else {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                if (item.getThumbnailBitmap() != null) {
                    thumbnailImageView.setImageBitmap(item.getThumbnailBitmap());
                } else {
                    thumbnailImageView.setImageBitmap(null);
                    new ShowThumbnailsTask(activity, client, R.drawable.go_arrow)
                            .execute(new ThumbnailLoadAction(item, thumbnailImageView, position));
                }
            }

            // Set thumbnail background based on current theme
            if (Util.isLightTheme(settings.getTheme()))
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_light);
            else
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_dark);
        } else {
            // if thumbnails disabled, hide thumbnail icon
            thumbnailContainer.setVisibility(View.GONE);
        }
    }
}

From source file:org.kontalk.ui.GroupInfoFragment.java

private void showIdentityDialog(Contact c, boolean subscribed) {
    final String jid = c.getJID();
    final String dialogFingerprint;
    final String fingerprint;
    final boolean selfJid = Authenticator.isSelfJID(getContext(), jid);
    int titleResId = R.string.title_identity;
    String uid;/*from   w  ww .ja  v a2  s  .  co m*/

    PGPPublicKeyRing publicKey = Keyring.getPublicKey(getContext(), jid, MyUsers.Keys.TRUST_UNKNOWN);
    if (publicKey != null) {
        PGPPublicKey pk = PGP.getMasterKey(publicKey);
        String rawFingerprint = PGP.getFingerprint(pk);
        fingerprint = PGP.formatFingerprint(rawFingerprint);

        uid = PGP.getUserId(pk, XmppStringUtils.parseDomain(jid));
        dialogFingerprint = selfJid ? null : rawFingerprint;
    } else {
        // FIXME using another string
        fingerprint = getString(R.string.peer_unknown);
        uid = null;
        dialogFingerprint = null;
    }

    if (Authenticator.isSelfJID(getContext(), jid)) {
        titleResId = R.string.title_identity_self;
    }

    SpannableStringBuilder text = new SpannableStringBuilder();

    if (c.getName() != null && c.getNumber() != null) {
        text.append(c.getName()).append('\n').append(c.getNumber());
    } else {
        int start = text.length();
        text.append(uid != null ? uid : c.getJID());
        text.setSpan(SystemUtils.getTypefaceSpan(Typeface.BOLD), start, text.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    text.append('\n').append(getString(R.string.text_invitation2)).append('\n');

    int start = text.length();
    text.append(fingerprint);
    text.setSpan(SystemUtils.getTypefaceSpan(Typeface.BOLD), start, text.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    int trustStringId;
    CharacterStyle[] trustSpans;

    if (subscribed) {
        int trustedLevel;
        if (c.isKeyChanged()) {
            // the key has changed and was not trusted yet
            trustedLevel = MyUsers.Keys.TRUST_UNKNOWN;
        } else {
            trustedLevel = c.getTrustedLevel();
        }

        switch (trustedLevel) {
        case MyUsers.Keys.TRUST_IGNORED:
            trustStringId = R.string.trust_ignored;
            trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD),
                    SystemUtils.getColoredSpan(getContext(), R.color.button_danger) };
            break;

        case MyUsers.Keys.TRUST_VERIFIED:
            trustStringId = R.string.trust_verified;
            trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD),
                    SystemUtils.getColoredSpan(getContext(), R.color.button_success) };
            break;

        case MyUsers.Keys.TRUST_UNKNOWN:
        default:
            trustStringId = R.string.trust_unknown;
            trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD),
                    SystemUtils.getColoredSpan(getContext(), R.color.button_danger) };
            break;
        }
    } else {
        trustStringId = R.string.status_notsubscribed;
        trustSpans = new CharacterStyle[] { SystemUtils.getTypefaceSpan(Typeface.BOLD), };
    }

    text.append('\n').append(getString(R.string.status_label));
    start = text.length();
    text.append(getString(trustStringId));
    for (CharacterStyle span : trustSpans)
        text.setSpan(span, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    MaterialDialog.Builder builder = new MaterialDialog.Builder(getContext()).content(text).title(titleResId);

    if (dialogFingerprint != null && subscribed) {
        builder.onAny(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                switch (which) {
                case POSITIVE:
                    // trust the key
                    trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_VERIFIED);
                    break;
                case NEUTRAL:
                    // ignore the key
                    trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_IGNORED);
                    break;
                case NEGATIVE:
                    // untrust the key
                    trustKey(jid, dialogFingerprint, MyUsers.Keys.TRUST_UNKNOWN);
                    break;
                }
            }
        }).positiveText(R.string.button_accept).positiveColorRes(R.color.button_success)
                .neutralText(R.string.button_ignore).negativeText(R.string.button_refuse)
                .negativeColorRes(R.color.button_danger);
    } else if (!selfJid) {
        builder.onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                openChat(jid);
            }
        }).positiveText(R.string.button_private_chat);
    }

    builder.show();
}

From source file:com.orangelabs.rcs.ri.messaging.chat.ChatCursorAdapter.java

/**
 * Format text with smiley//w w w .ja v  a  2s .c o  m
 * 
 * @param txt Text
 * @return String
 */
private CharSequence formatMessageWithSmiley(String txt) {
    SpannableStringBuilder buf = new SpannableStringBuilder();
    if (!TextUtils.isEmpty(txt)) {
        SmileyParser smileyParser = new SmileyParser(txt, mSmileyResources);
        smileyParser.parse();
        buf.append(smileyParser.getSpannableString(mContext));
    }
    return buf;
}

From source file:it.rainbowbreeze.keepmoving.ui.TimetableActivity.java

/**
 * Updates the text of the notification//  w  ww  . j  a v  a2  s .  c om
 */
private void updateNotification() {
    TimetableModel mModel = mController.getModel();

    // Get an instance of the NotificationManager service
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    if (mModel.hasNoRoutes() || mModel.hasInvalidLeavingTimestamp()) {
        notificationManager.cancel(Utils.NOTIFICATION_ID);
        return;
    }

    Route route = mModel.getRoutes().get(0);

    NotificationCompat.BigTextStyle stepsStyle = new NotificationCompat.BigTextStyle()
            .setBigContentTitle(getString(R.string.timetable_msgNotifStepsTitle));
    SpannableStringBuilder sb = new SpannableStringBuilder();
    for (GeoPoint point : route.getSteps()) {
        String line = String.format(getString(R.string.timetable_msgNotifStepsLine),
                point.isValidForAllTime() ? "--" : Utils.getTimeFromTimestamp(point.getValidTime()),
                point.getName(), point.getType().toString());
        sb.append(Html.fromHtml(line));
    }
    stepsStyle.bigText(sb);

    // Notification only for the wear
    Notification stepsNotif = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(String.format(getString(R.string.timetable_msgNotifTitle),
                    Utils.getRemainingMinutesToRoute(route)))
            .setContentText(String.format(getString(R.string.timetable_msgNotifContent),
                    Utils.getRemainingMinutesToRoute(route),
                    Utils.getTimeFromTimestamp(route.getArrivalTimestamp())))
            .setStyle(stepsStyle).build();

    WearableExtender extender = new WearableExtender().addPage(stepsNotif)
    //                .setHintHideIcon(true)
    ;

    // Notification displayed on the device
    Notification nextMoveNotif = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(String.format(getString(R.string.timetable_msgNotifTitle),
                    Utils.getRemainingMinutesToRoute(route)))
            .setContentText(String.format(getString(R.string.timetable_msgNotifContent),
                    Utils.getRemainingMinutesToRoute(route),
                    Utils.getTimeFromTimestamp(route.getArrivalTimestamp())))
            .extend(extender).build();

    // Build the notification and issues it with notification manager.
    notificationManager.notify(Utils.NOTIFICATION_ID, nextMoveNotif);
}

From source file:org.sufficientlysecure.keychain.ui.ViewKeyKeybaseFragment.java

@Override
public void onCryptoOperationSuccess(KeybaseVerificationResult result) {

    result.createNotify(getActivity()).show();

    String proofUrl = result.mProofUrl;
    String presenceUrl = result.mPresenceUrl;
    String presenceLabel = result.mPresenceLabel;

    Proof proof = mProof; // TODO: should ideally be contained in result

    String proofLabel;/*from   w  w  w .j  av a2  s .  com*/
    switch (proof.getType()) {
    case Proof.PROOF_TYPE_TWITTER:
        proofLabel = getString(R.string.keybase_twitter_proof);
        break;
    case Proof.PROOF_TYPE_DNS:
        proofLabel = getString(R.string.keybase_dns_proof);
        break;
    case Proof.PROOF_TYPE_WEB_SITE:
        proofLabel = getString(R.string.keybase_web_site_proof);
        break;
    case Proof.PROOF_TYPE_GITHUB:
        proofLabel = getString(R.string.keybase_github_proof);
        break;
    case Proof.PROOF_TYPE_REDDIT:
        proofLabel = getString(R.string.keybase_reddit_proof);
        break;
    default:
        proofLabel = getString(R.string.keybase_a_post);
        break;
    }

    SpannableStringBuilder ssb = new SpannableStringBuilder();

    ssb.append(getString(R.string.keybase_proof_succeeded));
    StyleSpan bold = new StyleSpan(Typeface.BOLD);
    ssb.setSpan(bold, 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.append("\n\n");
    int length = ssb.length();
    ssb.append(proofLabel);
    if (proofUrl != null) {
        URLSpan postLink = new URLSpan(proofUrl);
        ssb.setSpan(postLink, length, length + proofLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    if (Proof.PROOF_TYPE_DNS == proof.getType()) {
        ssb.append(" ").append(getString(R.string.keybase_for_the_domain)).append(" ");
    } else {
        ssb.append(" ").append(getString(R.string.keybase_fetched_from)).append(" ");
    }
    length = ssb.length();
    URLSpan presenceLink = new URLSpan(presenceUrl);
    ssb.append(presenceLabel);
    ssb.setSpan(presenceLink, length, length + presenceLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    if (Proof.PROOF_TYPE_REDDIT == proof.getType()) {
        ssb.append(", ").append(getString(R.string.keybase_reddit_attribution)).append(" ")
                .append(proof.getHandle()).append("?, ");
    }
    ssb.append(" ").append(getString(R.string.keybase_contained_signature));

    displaySpannableResult(ssb);
}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

private void onNotify(final Cursor upcomingEpisodes, List<Integer> notifyPositions, long latestAirtime) {
    final Context context = getApplicationContext();

    CharSequence tickerText;/*w w  w  .  j  a  v  a2s .c  o  m*/
    CharSequence contentTitle;
    CharSequence contentText;
    PendingIntent contentIntent;
    // base intent for task stack
    final Intent showsIntent = new Intent(context, ShowsActivity.class);
    showsIntent.putExtra(ShowsActivity.InitBundle.SELECTED_TAB, ShowsActivity.InitBundle.INDEX_TAB_UPCOMING);

    final int count = notifyPositions.size();
    if (count == 1) {
        // notify in detail about one episode
        Timber.d("Notifying about 1 new episode");
        upcomingEpisodes.moveToPosition(notifyPositions.get(0));

        final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
        tickerText = getString(R.string.upcoming_show, showTitle);
        contentTitle = showTitle + " "
                + Utils.getEpisodeNumber(this, upcomingEpisodes.getInt(NotificationQuery.SEASON),
                        upcomingEpisodes.getInt(NotificationQuery.NUMBER));

        // "8:00 PM on Network"
        final String releaseTime = TimeTools.formatToLocalReleaseTime(this, TimeTools.getEpisodeReleaseTime(
                this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
        final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
        contentText = getString(R.string.upcoming_show_detailed, releaseTime, network);

        Intent episodeDetailsIntent = new Intent(context, EpisodesActivity.class);
        episodeDetailsIntent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID,
                upcomingEpisodes.getInt(NotificationQuery._ID));
        episodeDetailsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);

        contentIntent = TaskStackBuilder.create(context).addNextIntent(showsIntent)
                .addNextIntent(episodeDetailsIntent)
                .getPendingIntent(REQUEST_CODE_SINGLE_EPISODE, PendingIntent.FLAG_CANCEL_CURRENT);
    } else {
        // notify about multiple episodes
        Timber.d("Notifying about " + count + " new episodes");
        tickerText = getString(R.string.upcoming_episodes);
        contentTitle = getString(R.string.upcoming_episodes_number, count);
        contentText = getString(R.string.upcoming_display);

        contentIntent = TaskStackBuilder.create(context)
                .addNextIntent(showsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime))
                .getPendingIntent(REQUEST_CODE_MULTIPLE_EPISODES, PendingIntent.FLAG_CANCEL_CURRENT);
    }

    final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);

    if (AndroidUtils.isJellyBeanOrHigher()) {
        Timber.d("Building rich notification (JB+)");
        // JELLY BEAN and above
        if (count == 1) {
            // single episode
            upcomingEpisodes.moveToPosition(notifyPositions.get(0));
            maybeSetPoster(context, nb, upcomingEpisodes.getString(NotificationQuery.POSTER));

            final String episodeTitle = upcomingEpisodes.getString(NotificationQuery.TITLE);
            final String episodeSummary = upcomingEpisodes.getString(NotificationQuery.OVERVIEW);

            final SpannableStringBuilder bigText = new SpannableStringBuilder();
            bigText.append(TextUtils.isEmpty(episodeTitle) ? "" : episodeTitle);
            bigText.setSpan(new StyleSpan(Typeface.BOLD), 0, bigText.length(), 0);
            bigText.append("\n");
            bigText.append(TextUtils.isEmpty(episodeSummary) ? "" : episodeSummary);

            nb.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(contentText));

            // Action button to check in
            Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class);
            checkInActionIntent.putExtra(QuickCheckInActivity.InitBundle.EPISODE_TVDBID,
                    upcomingEpisodes.getInt(NotificationQuery._ID));
            checkInActionIntent
                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            PendingIntent checkInIntent = PendingIntent.getActivity(context, REQUEST_CODE_ACTION_CHECKIN,
                    checkInActionIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin), checkInIntent);
        } else {
            // multiple episodes
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

            // display at most the first five
            for (int displayIndex = 0; displayIndex < Math.min(count, 5); displayIndex++) {
                if (!upcomingEpisodes.moveToPosition(notifyPositions.get(displayIndex))) {
                    // could not go to the desired position (testing just in case)
                    break;
                }

                final SpannableStringBuilder lineText = new SpannableStringBuilder();

                // show title
                String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
                lineText.append(TextUtils.isEmpty(showTitle) ? "" : showTitle);
                lineText.setSpan(new StyleSpan(Typeface.BOLD), 0, lineText.length(), 0);

                lineText.append(" ");

                // "8:00 PM on Network"
                String releaseTime = TimeTools.formatToLocalReleaseTime(this, TimeTools.getEpisodeReleaseTime(
                        this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
                String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
                lineText.append(getString(R.string.upcoming_show_detailed, releaseTime, network));

                inboxStyle.addLine(lineText);
            }

            // tell if we could not display all episodes
            if (count > 5) {
                inboxStyle.setSummaryText(getString(R.string.more, count - 5));
            }

            nb.setStyle(inboxStyle);
            nb.setContentInfo(String.valueOf(count));
        }
    } else {
        // ICS and below
        if (count == 1) {
            // single episode
            upcomingEpisodes.moveToPosition(notifyPositions.get(0));
            maybeSetPoster(context, nb, upcomingEpisodes.getString(NotificationQuery.POSTER));
        }
    }

    // notification sound
    final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context);
    // If the string is empty, the user chose silent...
    if (ringtoneUri.length() != 0) {
        // ...otherwise set the specified ringtone
        Timber.d("Notification has sound");
        nb.setSound(Uri.parse(ringtoneUri));
    }
    // vibration
    if (NotificationSettings.isNotificationVibrating(context)) {
        Timber.d("Notification vibrates");
        nb.setVibrate(VIBRATION_PATTERN);
    }
    nb.setDefaults(Notification.DEFAULT_LIGHTS);
    nb.setWhen(System.currentTimeMillis());
    nb.setAutoCancel(true);
    nb.setTicker(tickerText);
    nb.setContentTitle(contentTitle);
    nb.setContentText(contentText);
    nb.setContentIntent(contentIntent);
    nb.setSmallIcon(R.drawable.ic_notification);
    nb.setColor(getResources().getColor(R.color.accent_primary));
    nb.setPriority(NotificationCompat.PRIORITY_DEFAULT);
    nb.setCategory(NotificationCompat.CATEGORY_EVENT);

    Timber.d("Setting delete intent with episode time: " + latestAirtime);
    Intent i = new Intent(this, NotificationService.class);
    i.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
    PendingIntent deleteIntent = PendingIntent.getService(this, REQUEST_CODE_DELETE_INTENT, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
    nb.setDeleteIntent(deleteIntent);

    // build the notification
    Notification notification = nb.build();

    // use string resource id, always unique within app
    final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(R.string.upcoming_show, notification);
}

From source file:com.todoroo.astrid.adapter.UpdateAdapter.java

public static Spanned getUpdateComment(final AstridActivity context, UserActivity activity, User user,
        String linkColor, String fromView) {
    String userDisplay;// www  .j  av  a2 s . c  o  m
    if (activity.getValue(UserActivity.USER_UUID).equals(Task.USER_ID_SELF)) {
        userDisplay = context.getString(R.string.update_string_user_self);
    } else if (user == null) {
        userDisplay = context.getString(R.string.ENA_no_user);
    } else {
        userDisplay = user.getDisplayName(USER_NAME, USER_FIRST_NAME, USER_LAST_NAME);
    }
    if (TextUtils.isEmpty(userDisplay))
        userDisplay = context.getString(R.string.ENA_no_user);
    String targetName = activity.getValue(UserActivity.TARGET_NAME);
    String action = activity.getValue(UserActivity.ACTION);
    String message = activity.getValue(UserActivity.MESSAGE);

    int commentResource = 0;
    if (UserActivity.ACTION_TASK_COMMENT.equals(action)) {
        if (fromView.equals(FROM_TASK_VIEW) || TextUtils.isEmpty(targetName))
            commentResource = R.string.update_string_default_comment;
        else
            commentResource = R.string.update_string_task_comment;
    } else if (UserActivity.ACTION_TAG_COMMENT.equals(action)) {
        if (fromView.equals(FROM_TAG_VIEW) || TextUtils.isEmpty(targetName))
            commentResource = R.string.update_string_default_comment;
        else
            commentResource = R.string.update_string_tag_comment;
    }

    if (commentResource == 0)
        return Html.fromHtml(String.format("%s %s", userDisplay, message)); //$NON-NLS-1$

    String original = context.getString(commentResource, userDisplay, targetName, message);
    int taskLinkIndex = original.indexOf(TARGET_LINK_PREFIX);

    if (taskLinkIndex < 0)
        return Html.fromHtml(original);

    String[] components = original.split(" "); //$NON-NLS-1$
    SpannableStringBuilder builder = new SpannableStringBuilder();
    StringBuilder htmlStringBuilder = new StringBuilder();

    for (String comp : components) {
        Matcher m = TARGET_LINK_PATTERN.matcher(comp);
        if (m.find()) {
            builder.append(Html.fromHtml(htmlStringBuilder.toString()));
            htmlStringBuilder.setLength(0);

            String linkType = m.group(1);
            CharSequence link = getLinkSpan(context, activity, targetName, linkColor, linkType);
            if (link != null) {
                builder.append(link);
                if (!m.hitEnd()) {
                    builder.append(comp.substring(m.end()));
                }
                builder.append(' ');
            }
        } else {
            htmlStringBuilder.append(comp);
            htmlStringBuilder.append(' ');
        }
    }

    if (htmlStringBuilder.length() > 0)
        builder.append(Html.fromHtml(htmlStringBuilder.toString()));

    return builder;
}

From source file:com.github.andrewlord1990.snackbarbuilder.SnackbarBuilder.java

private void initialiseAppendMessages() {
    if (appendMessages == null) {
        appendMessages = new SpannableStringBuilder();
    }
}

From source file:org.sufficientlysecure.keychain.ui.ViewKeyKeybaseFragment.java

@Override
public void onCryptoOperationError(KeybaseVerificationResult result) {

    result.createNotify(getActivity()).show();

    SpannableStringBuilder ssb = new SpannableStringBuilder();

    ssb.append(getString(R.string.keybase_proof_failure));
    String msg = getString(result.getLog().getLast().mType.mMsgId);
    if (msg == null) {
        msg = getString(R.string.keybase_unknown_proof_failure);
    }/*from   w  w w. j av  a 2s  .c o  m*/
    StyleSpan bold = new StyleSpan(Typeface.BOLD);
    ssb.setSpan(bold, 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.append("\n\n").append(msg);

    displaySpannableResult(ssb);
}