Example usage for android.text SpannableString SpannableString

List of usage examples for android.text SpannableString SpannableString

Introduction

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

Prototype

public SpannableString(CharSequence source) 

Source Link

Document

For the backward compatibility reasons, this constructor copies all spans including android.text.NoCopySpan .

Usage

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

public CharSequence getBestDayText() {

    final List<PickupInfo> urgent = pickupUtils.urgentMeds();
    Pair<LocalDate, List<PickupInfo>> best = pickupUtils.getBestDay();

    final List<PickupInfo> next = (best == null || best.first == null) ? new ArrayList<PickupInfo>()
            : best.second;/*from   www .  j a  v  a 2 s  .  c  om*/

    CharSequence msg = new SpannableString("No hai medicinas que recoger");
    LocalDate today = LocalDate.now();

    // there are not urgent meds, but there are others to pickup
    if (urgent.isEmpty() && best != null) {

        //            Log.d("Calendar", "Urgent: " + urgent.size());
        //            Log.d("Calendar", "Next: " + next.size());

        Log.d("Calendar", "there are not urgent meds, but there are others to pickup");
        if (next.size() > 1) {
            msg = new SpannableString(getString(R.string.best_single_day_messge,
                    best.first.toString(getString(R.string.best_date_format)), next.size()) + "\n\n");
        } else {
            msg = new SpannableString(getString(R.string.best_single_day_messge_one_med,
                    best.first.toString(getString(R.string.best_date_format))) + "\n\n");
        }
        msg = addPickupList(msg, next);
    }

    // there are urgent meds
    Log.d("Calendar", "there are urgent meds");
    if (!urgent.isEmpty()) {
        // and others
        Log.d("Calendar", "and others");
        if (best != null) {

            String bestStr = best.equals(LocalDate.now().plusDays(1))
                    ? getString(R.string.calendar_date_tomorrow)
                    : best.first.toString(getString(R.string.best_date_format));

            // and the others date is near
            Log.d("Calendar", "and the others date is near");
            if (today.plusDays(3).isAfter(best.first)) {
                List<PickupInfo> all = new ArrayList<>();
                all.addAll(urgent);
                all.addAll(next);
                msg = new SpannableString(
                        getString(R.string.best_single_day_messge, bestStr, all.size()) + "\n\n");
                msg = addPickupList(msg, all);
            }
            // and the others date is not near
            else {

                Log.d("Calendar", "and the others date is not near");
                msg = addPickupList(new SpannableString(getString(R.string.pending_meds_msg) + "\n\n"), urgent);

                msg = TextUtils.concat(msg, new SpannableString("\n"));
                if (next.size() > 1) {
                    Log.d("Calendar", " size > 1");
                    msg = TextUtils.concat(msg,
                            getString(R.string.best_single_day_messge_after_pending, bestStr, next.size())
                                    + "\n\n");
                } else {
                    Log.d("Calendar", " size <= 1");
                    msg = TextUtils.concat(msg,
                            getString(R.string.best_single_day_messge_after_pending_one_med, bestStr) + "\n\n");
                }
                msg = addPickupList(msg, next);
            }
        } else {
            Log.d("Calendar", " there are only urgent meds");
            // there are only urgent meds
            msg = addPickupList(getString(R.string.pending_meds_msg) + "\n\n", urgent);
        }
    }

    Log.d("BEST_DAY", msg.toString());
    return msg;
}

From source file:im.vector.notifications.NotificationUtils.java

/**
 * Add a text style for a bunch of notified events.
 * <p>/*from   w  w w  .  j  a va  2s .co m*/
 * The notification contains the notified messages from any rooms.
 * It does not contain anymore the latest notified message.
 * <p>
 * When there is only one room, it displays the MAX_NUMBER_NOTIFICATION_LINES latest messages.
 * The busy ones are displayed in RED.
 * The QUICK REPLY and other buttons are displayed.
 * <p>
 * When there are several rooms, it displays the busy notified rooms first (sorted by latest message timestamp).
 * Each line is
 * - "Room Name : XX unread messages" if there are many unread messages
 * - 'Room Name : Sender   - Message body" if there is only one unread message.
 *
 * @param context            the context
 * @param builder            the notification builder
 * @param roomsNotifications the rooms notifications
 */
private static void addTextStyle(Context context, NotificationCompat.Builder builder,
        RoomsNotifications roomsNotifications) {

    // nothing to do
    if (0 == roomsNotifications.mRoomNotifications.size()) {
        return;
    }

    // when there are several rooms, the text style is not the same
    if (roomsNotifications.mRoomNotifications.size() > 1) {
        addTextStyleWithSeveralRooms(context, builder, roomsNotifications);
        return;
    }

    SpannableString latestText = null;
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    for (CharSequence sequence : roomsNotifications.mReversedMessagesList) {
        inboxStyle.addLine(latestText = new SpannableString(sequence));
    }

    inboxStyle.setBigContentTitle(roomsNotifications.mContentTitle);

    // adapt the notification display to the number of notified messages
    if ((1 == roomsNotifications.mReversedMessagesList.size()) && (null != latestText)) {
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(latestText));
    } else {
        if (!TextUtils.isEmpty(roomsNotifications.mSummaryText)) {
            inboxStyle.setSummaryText(roomsNotifications.mSummaryText);
        }
        builder.setStyle(inboxStyle);
    }

    // do not offer to quick respond if the user did not dismiss the previous one
    if (!LockScreenActivity.isDisplayingALockScreenActivity()) {
        if (!roomsNotifications.mIsInvitationEvent) {

            // offer to type a quick answer (i.e. without launching the application)
            Intent quickReplyIntent = new Intent(context, LockScreenActivity.class);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_ROOM_ID, roomsNotifications.mRoomId);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_SENDER_NAME, roomsNotifications.mSenderName);
            quickReplyIntent.putExtra(LockScreenActivity.EXTRA_MESSAGE_BODY,
                    roomsNotifications.mQuickReplyBody);

            // the action must be unique else the parameters are ignored
            quickReplyIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
            PendingIntent pIntent = PendingIntent.getActivity(context, 0, quickReplyIntent, 0);
            builder.addAction(R.drawable.vector_notification_quick_reply,
                    context.getString(R.string.action_quick_reply), pIntent);
        } else {
            {
                // offer to type a quick reject button
                Intent leaveIntent = new Intent(context, JoinScreenActivity.class);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_ROOM_ID, roomsNotifications.mRoomId);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_MATRIX_ID, roomsNotifications.mSessionId);
                leaveIntent.putExtra(JoinScreenActivity.EXTRA_REJECT, true);

                // the action must be unique else the parameters are ignored
                leaveIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
                PendingIntent pIntent = PendingIntent.getActivity(context, 0, leaveIntent, 0);
                builder.addAction(R.drawable.vector_notification_reject_invitation,
                        context.getString(R.string.reject), pIntent);
            }

            {
                // offer to type a quick accept button
                Intent acceptIntent = new Intent(context, JoinScreenActivity.class);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_ROOM_ID, roomsNotifications.mRoomId);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_MATRIX_ID, roomsNotifications.mSessionId);
                acceptIntent.putExtra(JoinScreenActivity.EXTRA_JOIN, true);

                // the action must be unique else the parameters are ignored
                acceptIntent.setAction(QUICK_LAUNCH_ACTION + ((int) (System.currentTimeMillis())));
                PendingIntent pIntent = PendingIntent.getActivity(context, 0, acceptIntent, 0);
                builder.addAction(R.drawable.vector_notification_accept_invitation,
                        context.getString(R.string.join), pIntent);
            }
        }

        // Build the pending intent for when the notification is clicked
        Intent roomIntentTap;

        if (roomsNotifications.mIsInvitationEvent) {
            // for invitation the room preview must be displayed
            roomIntentTap = CommonActivityUtils.buildIntentPreviewRoom(roomsNotifications.mSessionId,
                    roomsNotifications.mRoomId, context, VectorFakeRoomPreviewActivity.class);
        } else {
            roomIntentTap = new Intent(context, VectorRoomActivity.class);
            roomIntentTap.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomsNotifications.mRoomId);
        }
        // the action must be unique else the parameters are ignored
        roomIntentTap.setAction(TAP_TO_VIEW_ACTION + ((int) (System.currentTimeMillis())));

        // Recreate the back stack
        TaskStackBuilder stackBuilderTap = TaskStackBuilder.create(context)
                .addNextIntentWithParentStack(new Intent(context, VectorHomeActivity.class))
                .addNextIntent(roomIntentTap);

        builder.setContentIntent(stackBuilderTap.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

        builder.addAction(R.drawable.vector_notification_open, context.getString(R.string.action_open),
                stackBuilderTap.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

        // wearable
        if (!roomsNotifications.mIsInvitationEvent) {
            try {
                NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
                NotificationCompat.Action action = new NotificationCompat.Action.Builder(
                        R.drawable.message_notification_transparent, roomsNotifications.mWearableMessage,
                        stackBuilderTap.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)).build();
                wearableExtender.addAction(action);
                builder.extend(wearableExtender);
            } catch (Exception e) {
                Log.e(LOG_TAG, "## addTextStyleWithSeveralRooms() : WearableExtender failed " + e.getMessage());
            }
        }
    }
}

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

public static SpannableString toFriendlySnackbarString(Context context, String input) {
    final ForegroundColorSpan whiteSpan = new ForegroundColorSpan(
            ContextCompat.getColor(context, R.color.colorAccent));
    final SpannableString snackbarText = new SpannableString(input);
    snackbarText.setSpan(whiteSpan, 0, snackbarText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    return snackbarText;
}

From source file:fr.tvbarthel.apps.simpleweatherforcast.MainActivity.java

private void setActionBarTitle(int position) {
    String newTitle = getActionBarTitle(position);
    if (mActionBarSpannableTitle == null || !mActionBarSpannableTitle.toString().equals(newTitle)) {
        mActionBarSpannableTitle = new SpannableString(newTitle);
        mActionBarSpannableTitle.setSpan(mTypefaceSpanLight, 0, mActionBarSpannableTitle.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }//from  w ww.j a  va2s.  c  o m
}

From source file:com.razza.apps.iosched.myschedule.MyScheduleActivity.java

private void showAnnouncementDialogIfNeeded(Intent intent) {
    final String title = intent.getStringExtra(EXTRA_DIALOG_TITLE);
    final String message = intent.getStringExtra(EXTRA_DIALOG_MESSAGE);

    if (!mShowedAnnouncementDialog && !TextUtils.isEmpty(title) && !TextUtils.isEmpty(message)) {
        LogUtils.LOGD(TAG, "showAnnouncementDialogIfNeeded, title: " + title);
        LogUtils.LOGD(TAG, "showAnnouncementDialogIfNeeded, message: " + message);
        final String yes = intent.getStringExtra(EXTRA_DIALOG_YES);
        LogUtils.LOGD(TAG, "showAnnouncementDialogIfNeeded, yes: " + yes);
        final String no = intent.getStringExtra(EXTRA_DIALOG_NO);
        LogUtils.LOGD(TAG, "showAnnouncementDialogIfNeeded, no: " + no);
        final String url = intent.getStringExtra(EXTRA_DIALOG_URL);
        LogUtils.LOGD(TAG, "showAnnouncementDialogIfNeeded, url: " + url);
        final SpannableString spannable = new SpannableString(message == null ? "" : message);
        Linkify.addLinks(spannable, Linkify.WEB_URLS);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (!TextUtils.isEmpty(title)) {
            builder.setTitle(title);// www  . java 2  s.c om
        }
        builder.setMessage(spannable);
        if (!TextUtils.isEmpty(no)) {
            builder.setNegativeButton(no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
        }
        if (!TextUtils.isEmpty(yes)) {
            builder.setPositiveButton(yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }
            });
        }
        final AlertDialog dialog = builder.create();
        dialog.show();
        final TextView messageView = (TextView) dialog.findViewById(android.R.id.message);
        if (messageView != null) {
            // makes the embedded links in the text clickable, if there are any
            messageView.setMovementMethod(LinkMovementMethod.getInstance());
        }
        mShowedAnnouncementDialog = true;
    }
}

From source file:com.bt.heliniumstudentapp.SettingsActivity.java

private void setToolbar() {
    toolbarTB.setBackgroundColor(ContextCompat.getColor(this, MainActivity.primaryColor));

    MainActivity.setStatusBar(this);

    toolbarTB.getNavigationIcon().setColorFilter(ContextCompat.getColor(this, MainActivity.primaryTextColor),
            PorterDuff.Mode.SRC_ATOP);//from   www  .  j a va  2 s. co  m

    Spannable toolbarTitle = new SpannableString(getString(R.string.settings));
    toolbarTitle.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, MainActivity.primaryTextColor)),
            0, toolbarTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    toolbarTB.setTitle(toolbarTitle);
}

From source file:com.coderdojo.libretalk.MainActivity.java

private final void printMsg(final LibretalkMessageData message) {
    ArrayAdapter<SpannableString> adapter = new ArrayAdapter<SpannableString>(this,
            android.R.layout.simple_list_item_1, mMessageListArray);
    ListView listView = (ListView) findViewById(R.id.message_list);
    listView.setAdapter(adapter);/*  w ww. j av  a2  s .  c o m*/
    listView.setStackFromBottom(true);

    final String sourceMessage = message.getSenderTag() + ": " + message.getData();
    final SpannableString formattedText = new SpannableString(sourceMessage);

    if (message.getData().startsWith(">")) {

        formattedText.setSpan(
                new ForegroundColorSpan(LibretalkMessageData.getColorFromString(message.getSenderTag())),
                sourceMessage.indexOf(message.getSenderTag()),
                sourceMessage.indexOf(message.getSenderTag()) + message.getSenderTag().length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        formattedText.setSpan(new ForegroundColorSpan(Color.rgb(120, 153, 34)),
                sourceMessage.indexOf(message.getData()),
                sourceMessage.indexOf(message.getData()) + message.getData().length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {

        formattedText.setSpan(
                new ForegroundColorSpan(LibretalkMessageData.getColorFromString(message.getSenderTag())),
                sourceMessage.indexOf(message.getSenderTag()),
                sourceMessage.indexOf(message.getSenderTag()) + message.getSenderTag().length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    mMessageListArray.add(formattedText);
    adapter.notifyDataSetChanged();
}

From source file:org.mozilla.focus.fragment.UrlInputFragment.java

@Override
public void onFilter(String searchText, InlineAutocompleteEditText view) {
    // If the UrlInputFragment has already been hidden, don't bother with filtering. Because of the text
    // input architecture on Android it's possible for onFilter() to be called after we've already
    // hidden the Fragment, see the relevant bug for more background:
    // https://github.com/mozilla-mobile/focus-android/issues/441#issuecomment-293691141
    if (!isVisible()) {
        return;/*  ww w .ja va 2 s  . c o m*/
    }

    urlAutoCompleteFilter.onFilter(searchText, view);

    if (searchText.length() == 0) {
        clearView.setVisibility(View.GONE);
        searchViewContainer.setVisibility(View.GONE);
    } else {
        clearView.setVisibility(View.VISIBLE);

        final String hint = getString(R.string.search_hint, searchText);

        final SpannableString content = new SpannableString(hint);
        content.setSpan(new StyleSpan(Typeface.BOLD), hint.length() - searchText.length(), hint.length(), 0);

        searchView.setText(content);
        searchViewContainer.setVisibility(View.VISIBLE);
    }
}

From source file:com.avapira.bobroreader.hanabira.HanabiraParser.java

@SuppressWarnings("ConstantConditions")
private void replaceAll(String begin, String end, SpanObjectFactory factory, int flag) {
    int removedFormatCharsDelta = 0;
    Pattern pattern = Pattern.compile(String.format("(%s)(.+?)(%s)", begin, end), Pattern.MULTILINE | flag);
    String beginRestore = restoreBreaks(begin);
    String endRestore = restoreBreaks(end);
    Matcher matcher = pattern.matcher(builder);
    String inlinedString;/*  w w  w .  java2 s.co m*/

    boolean code = begin.contains("`");
    while (matcher.find()) {
        int start = matcher.start(2);
        int finish = matcher.end(2);

        // don't reformat in code blocks
        if (!code) {
            CodeBlockSpan[] spans = builder.getSpans(start, finish, CodeBlockSpan.class);
            if (spans != null && spans.length != 0) {
                continue;
            }
        }

        // don't reformat double borders while searchin for sinlges
        // e.g.: searching for "*abc*", found "**"
        inlinedString = matcher.group(2);
        if (inlinedString == null || "".equals(inlinedString)) {
            System.out.println(matcher.group());
            continue;
        }

        int lengthPrefix = matcher.group(1).length();
        builder.replace(matcher.start(1) - removedFormatCharsDelta, matcher.end(1) - removedFormatCharsDelta,
                beginRestore);

        builder.replace(matcher.start(3) - lengthPrefix - removedFormatCharsDelta + beginRestore.length(),
                matcher.end(3) - lengthPrefix - removedFormatCharsDelta + beginRestore.length(), endRestore);

        SpannableString rep = new SpannableString(matcher.group(2));
        rep.setSpan(factory.getSpan(), 0, rep.length(), 0);
        if (!code) {
            Linkify.addLinks(rep, Linkify.WEB_URLS);
            // fixme twice used Linkify? try remove and just setSpan to builder
        }
        builder.replace(matcher.start() - removedFormatCharsDelta + beginRestore.length(),
                matcher.start() + rep.length() - removedFormatCharsDelta + endRestore.length(), rep);

        // store deletions
        removedFormatCharsDelta += matcher.group(1).length() - beginRestore.length();
        removedFormatCharsDelta += matcher.group(3).length() - endRestore.length();
    }
}

From source file:im.ene.lab.attiq.ui.activities.ProfileActivity.java

@SuppressWarnings("unused")
public void onEventMainThread(ProfileUpdatedEvent event) {
    mProfileName.setText(mProfile.getUserName());
    mProfileDescription.setText(mProfile.getBrief());

    final RequestCreator profileImageRequest;
    if (!UIUtil.isEmpty(mProfile.getProfileImageUrl())) {
        profileImageRequest = Attiq.picasso().load(mProfile.getProfileImageUrl());
    } else {/*from ww  w .jav a2 s  .co m*/
        profileImageRequest = Attiq.picasso().load(R.drawable.blank_profile_icon_large);
    }

    profileImageRequest.placeholder(R.drawable.blank_profile_icon_large)
            .error(R.drawable.blank_profile_icon_large).resize(mProfileImageSize, 0)
            .transform(new RoundedTransformation(0, mImageBorderColor, mProfileImageRadius))
            .into(mProfileImage);

    mSpannableTitle = new SpannableString(mUserId);
    if (!UIUtil.isEmpty(mProfile.getFullName())) {
        mSpannableSubtitle = new SpannableString(mProfile.getFullName());
    }

    updateTitle();
    updateDescription();
    updateQuantities();
    updateSocialButtons();
}