Example usage for android.text Spannable setSpan

List of usage examples for android.text Spannable setSpan

Introduction

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

Prototype

public void setSpan(Object what, int start, int end, int flags);

Source Link

Document

Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere.

Usage

From source file:com.orange.ocara.ui.activity.BaseActivityManagingAudit.java

public void showAuditObjectProgress(AuditObject auditObject, final boolean terminateActivityWhenDone) {
    CharSequence info = getText(com.orange.ocara.R.string.auditing_progress_info);

    Spannable auditingStatus = new SpannableString("");
    int color = getResources().getColor(com.orange.ocara.R.color.black);
    switch (auditObject.getResponse()) {
    case OK:/*from  w  w w  . j  a  va2  s .  c o m*/
        auditingStatus = new SpannableString(getText(com.orange.ocara.R.string.auditing_progress_status_ok));
        color = getResources().getColor(com.orange.ocara.R.color.green);
        break;
    case NOK:
        if (auditObject.hasAtLeastOneBlockingRule()) {
            auditingStatus = new SpannableString(
                    getText(com.orange.ocara.R.string.auditing_progress_status_nok));
            color = getResources().getColor(com.orange.ocara.R.color.red);
        } else {

            auditingStatus = new SpannableString(
                    getText(com.orange.ocara.R.string.auditing_progress_status_anoying));
            color = getResources().getColor(com.orange.ocara.R.color.orange);
        }
        break;
    case DOUBT:
        auditingStatus = new SpannableString(getText(com.orange.ocara.R.string.auditing_progress_status_doubt));
        color = getResources().getColor(com.orange.ocara.R.color.yellow);
        break;
    case NoAnswer:
        auditingStatus = new SpannableString(
                getText(com.orange.ocara.R.string.auditing_progress_status_no_answer));
        color = getResources().getColor(com.orange.ocara.R.color.blue);
        break;
    }

    auditingStatus.setSpan(new ForegroundColorSpan(color), info.length(), auditingStatus.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    StringBuffer stringBuffer = new StringBuffer(info);
    stringBuffer.append("<br>").append(auditingStatus);

    // get application preference to know if he wants to audit object now

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    int displayAuditingProgessDialog = Integer.parseInt(sharedPreferences
            .getString(getString(com.orange.ocara.R.string.setting_display_auditing_progress_key), "1"));

    switch (displayAuditingProgessDialog) {
    case 1:
        final NotificationDialogBuilder dialogBuilder = new NotificationDialogBuilder(this);
        final AlertDialog dialog = dialogBuilder.setInfo(auditingStatus)
                .setOption(getString(com.orange.ocara.R.string.auditing_progress_option)).setCancelable(false)
                .setTitle(com.orange.ocara.R.string.auditing_progress_title)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {

                        auditingProgressDismiss(dialogBuilder.getOptionValue());

                        if (terminateActivityWhenDone) {
                            BaseActivityManagingAudit.this.finish();
                        }
                    }
                }).setPositiveButton(com.orange.ocara.R.string.action_close, null).create();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                dialog.dismiss();
            }

        }, 3500);
        dialog.show();

        break;
    default:
        if (terminateActivityWhenDone) {
            BaseActivityManagingAudit.this.finish();
        }
        break;
    }

}

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

private int formatBadgeText(Spannable displayedStringBuilder, String badgeText) {
    final int badgeTextLength = (badgeText != null) ? badgeText.length() : 0;
    if (!TextUtils.isEmpty(badgeText)) {
        displayedStringBuilder.setSpan(TextAppearanceSpan.wrap(sBadgeTextSpan), 0, badgeTextLength,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        displayedStringBuilder.setSpan(TextAppearanceSpan.wrap(sBadgeBackgroundSpan), 0, badgeTextLength,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        displayedStringBuilder.setSpan(new BadgeSpan(displayedStringBuilder, this), 0, badgeTextLength,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }//from  ww w. j a v  a  2s.  com

    return badgeTextLength;
}

From source file:org.chromium.chrome.browser.omnibox.SuggestionView.java

private boolean applyHighlightToMatchRegions(Spannable str, List<MatchClassification> classifications) {
    boolean hasMatch = false;
    for (int i = 0; i < classifications.size(); i++) {
        MatchClassification classification = classifications.get(i);
        if ((classification.style & MatchClassificationStyle.MATCH) == MatchClassificationStyle.MATCH) {
            int matchStartIndex = classification.offset;
            int matchEndIndex;
            if (i == classifications.size() - 1) {
                matchEndIndex = str.length();
            } else {
                matchEndIndex = classifications.get(i + 1).offset;
            }/*  w  w  w  .ja  v a  2 s.c  om*/
            matchStartIndex = Math.min(matchStartIndex, str.length());
            matchEndIndex = Math.min(matchEndIndex, str.length());

            hasMatch = true;
            // Bold the part of the URL that matches the user query.
            str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), matchStartIndex, matchEndIndex,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return hasMatch;
}

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

private void createSubject(final boolean isUnread) {
    final String badgeText = mHeader.badgeText == null ? "" : mHeader.badgeText;
    String subject = filterTag(getContext(), mHeader.conversation.subject);
    subject = mAdapter.getBidiFormatter().unicodeWrap(subject);
    subject = Conversation.getSubjectForDisplay(mContext, badgeText, subject);
    final Spannable displayedStringBuilder = new SpannableString(subject);

    // since spans affect text metrics, add spans to the string before measure/layout or eliding

    final int badgeTextLength = formatBadgeText(displayedStringBuilder, badgeText);

    if (!TextUtils.isEmpty(subject)) {
        displayedStringBuilder.setSpan(
                TextAppearanceSpan.wrap(isUnread ? sSubjectTextUnreadSpan : sSubjectTextReadSpan),
                badgeTextLength, subject.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }/*w w  w .j  ava 2  s  . c  om*/
    if (isActivated() && showActivatedText()) {
        displayedStringBuilder.setSpan(sActivatedTextSpan, badgeTextLength, displayedStringBuilder.length(),
                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }

    final int subjectWidth = mCoordinates.subjectWidth;
    final int subjectHeight = mCoordinates.subjectHeight;
    mSubjectTextView.setLayoutParams(new ViewGroup.LayoutParams(subjectWidth, subjectHeight));
    mSubjectTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mCoordinates.subjectFontSize);
    layoutViewExactly(mSubjectTextView, subjectWidth, subjectHeight);

    mSubjectTextView.setText(displayedStringBuilder);
}

From source file:com.hughes.android.dictionary.DictionaryActivity.java

private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {
    // Saw from the source code that LinkMovementMethod sets the selection!
    // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    final Matcher matcher = CHAR_DASH.matcher(text);
    while (matcher.find()) {
        spannable.setSpan(new NonLinkClickableSpan(textColorFg), matcher.start(), matcher.end(),
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }//  www .  j  ava2 s.  c o  m
}

From source file:mobisocial.musubi.ui.util.EmojiSpannableFactory.java

public void updateSpannable(Spannable span) {
    Spannable source = span;/*from  w w  w .ja  va2  s .  c  o m*/
    for (int i = 0; i < source.length(); i++) {
        char high = source.charAt(i);
        if (high <= 127) {
            // fast exit ascii
            continue;
        }

        // Block until we're initialized
        waitForEmoji();

        long codePoint = high;
        if (Character.isHighSurrogate(high)) {
            char low = source.charAt(++i);
            codePoint = Character.toCodePoint(high, low);
            if (Character.isSurrogatePair(high, low)) {
                // from BMP
                if (!mEmojiMap.containsKey(codePoint)) {
                    if (i >= source.length() - 2) {
                        continue;
                    }
                    high = source.charAt(++i);
                    if (!Character.isHighSurrogate(high)) {
                        Log.w(TAG, "bad unicode character? " + high);
                        continue;
                    }
                    low = source.charAt(++i);
                    if (!Character.isSurrogatePair(high, low)) {
                        Log.d(TAG, "Bogus unicode surrogate " + high + ", " + low);
                        continue;
                    }
                    int codePoint2 = Character.toCodePoint(high, low);
                    //String label = String.format("U+%X U+%X", codePoint, codePoint2);
                    codePoint = ((long) codePoint << 16) | codePoint2;
                }
            } else {
                Log.d(TAG, "Bogus unicode");
            }
        }

        if (mEmojiMap.containsKey(codePoint)) {
            Bitmap b = mStickerCache.get(codePoint);
            if (b != null) {
                DynamicDrawableSpan im = createStickerSpan(b);
                span.setSpan(im, i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                Log.d(TAG, "failed to decode bitmap for codepoints: " + codePoint);
            }
        }
    }
}

From source file:com.hippo.nimingban.ui.ListActivity.java

private Spanned fixURLSpan(Spanned spanned) {
    Spannable spannable;
    if (spanned instanceof Spannable) {
        spannable = (Spannable) spanned;
    } else {/* ww  w  . jav  a  2 s  .com*/
        spannable = new SpannableString(spanned);
    }

    URLSpan[] urlSpans = spannable.getSpans(0, spanned.length(), URLSpan.class);
    if (urlSpans == null) {
        return spanned;
    }

    for (URLSpan urlSpan : urlSpans) {
        String url = urlSpan.getURL();
        if (TextUtils.isEmpty(url)) {
            spannable.removeSpan(urlSpan);
        }

        try {
            new URL(url);
        } catch (MalformedURLException e) {
            URL absoluteUrl;
            // It might be relative path
            try {
                // Use absolute url
                absoluteUrl = new URL(new URL(ACUrl.HOST), url);
                int start = spannable.getSpanStart(urlSpan);
                int end = spannable.getSpanEnd(urlSpan);
                spannable.removeSpan(urlSpan);
                spannable.setSpan(new URLSpan(absoluteUrl.toString()), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } catch (MalformedURLException e1) {
                // Can't get url
                spannable.removeSpan(urlSpan);
            }
        }
    }

    return spannable;
}

From source file:cgeo.geocaching.CacheDetailActivity.java

private static void fixTextColor(final Spannable spannable, final int backgroundColor) {
    final ForegroundColorSpan[] spans = spannable.getSpans(0, spannable.length(), ForegroundColorSpan.class);

    for (final ForegroundColorSpan span : spans) {
        if (ColorUtils.getContrastRatio(span.getForegroundColor(), backgroundColor) < CONTRAST_THRESHOLD) {
            final int start = spannable.getSpanStart(span);
            final int end = spannable.getSpanEnd(span);

            //  Assuming that backgroundColor can be either white or black,
            // this will set opposite background color (white for black and black for white)
            spannable.setSpan(new BackgroundColorSpan(backgroundColor ^ 0x00ffffff), start, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }/*w w w  .  ja  v a  2s  .co m*/
    }
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

private void showAccessNotification(int uid) {
    String name = TextUtils.join(", ", Util.getApplicationNames(uid, ServiceSinkhole.this));

    Intent main = new Intent(ServiceSinkhole.this, ActivityMain.class);
    main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
    PendingIntent pi = PendingIntent.getActivity(ServiceSinkhole.this, uid + 10000, main,
            PendingIntent.FLAG_UPDATE_CURRENT);

    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorOn, tv, true);
    int colorOn = tv.data;
    getTheme().resolveAttribute(R.attr.colorOff, tv, true);
    int colorOff = tv.data;

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_cloud_upload_white_24dp).setGroup("AccessAttempt")
            .setContentTitle(getString(R.string.app_name)).setContentText(getString(R.string.msg_access, name))
            .setContentIntent(pi).setColor(colorOff).setOngoing(false).setAutoCancel(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET);
    }//  ww  w .j  a v a 2s. com

    DateFormat df = new SimpleDateFormat("dd HH:mm");

    NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder);
    String sname = getString(R.string.msg_access, name);
    int pos = sname.indexOf(name);
    Spannable sp = new SpannableString(sname);
    sp.setSpan(new StyleSpan(Typeface.BOLD), pos, pos + name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    notification.addLine(sp);

    Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getAccessUnset(uid, 7);
    int colDAddr = cursor.getColumnIndex("daddr");
    int colTime = cursor.getColumnIndex("time");
    int colAllowed = cursor.getColumnIndex("allowed");
    while (cursor.moveToNext()) {
        StringBuilder sb = new StringBuilder();
        sb.append(df.format(cursor.getLong(colTime))).append(' ');

        String daddr = cursor.getString(colDAddr);
        if (Util.isNumericAddress(daddr))
            try {
                daddr = InetAddress.getByName(daddr).getHostName();
            } catch (UnknownHostException ignored) {
            }
        sb.append(daddr);

        int allowed = cursor.getInt(colAllowed);
        if (allowed >= 0) {
            pos = sb.indexOf(daddr);
            sp = new SpannableString(sb);
            ForegroundColorSpan fgsp = new ForegroundColorSpan(allowed > 0 ? colorOn : colorOff);
            sp.setSpan(fgsp, pos, pos + daddr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        notification.addLine(sp);
    }
    cursor.close();

    NotificationManagerCompat.from(this).notify(uid + 10000, notification.build());
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

private void showAccessNotification(int uid) {
    String name = TextUtils.join(", ", Util.getApplicationNames(uid, ServiceSinkhole.this));

    Intent main = new Intent(ServiceSinkhole.this, MainActivity.class);
    main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid));
    PendingIntent pi = PendingIntent.getActivity(ServiceSinkhole.this, uid + 10000, main,
            PendingIntent.FLAG_UPDATE_CURRENT);

    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorOn, tv, true);
    int colorOn = tv.data;
    getTheme().resolveAttribute(R.attr.colorOff, tv, true);
    int colorOff = tv.data;

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_cloud_upload_white_24dp).setGroup("AccessAttempt").setContentIntent(pi)
            .setColor(colorOff).setOngoing(false).setAutoCancel(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        builder.setContentTitle(name).setContentText(getString(R.string.msg_access_n));
    else/*w ww . j a va  2s. co  m*/
        builder.setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.msg_access, name));

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET);
    }

    DateFormat df = new SimpleDateFormat("dd HH:mm");

    NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        notification.addLine(getString(R.string.msg_access_n));
    else {
        String sname = getString(R.string.msg_access, name);
        int pos = sname.indexOf(name);
        Spannable sp = new SpannableString(sname);
        sp.setSpan(new StyleSpan(Typeface.BOLD), pos, pos + name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        notification.addLine(sp);
    }

    Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getAccessUnset(uid, 7);
    int colDAddr = cursor.getColumnIndex("daddr");
    int colTime = cursor.getColumnIndex("time");
    int colAllowed = cursor.getColumnIndex("allowed");
    while (cursor.moveToNext()) {
        StringBuilder sb = new StringBuilder();
        sb.append(df.format(cursor.getLong(colTime))).append(' ');

        String daddr = cursor.getString(colDAddr);
        if (Util.isNumericAddress(daddr))
            try {
                daddr = InetAddress.getByName(daddr).getHostName();
            } catch (UnknownHostException ignored) {
            }
        sb.append(daddr);

        int allowed = cursor.getInt(colAllowed);
        if (allowed >= 0) {
            int pos = sb.indexOf(daddr);
            Spannable sp = new SpannableString(sb);
            ForegroundColorSpan fgsp = new ForegroundColorSpan(allowed > 0 ? colorOn : colorOff);
            sp.setSpan(fgsp, pos, pos + daddr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            notification.addLine(sp);
        } else
            notification.addLine(sb);
    }
    cursor.close();

    NotificationManagerCompat.from(this).notify(uid + 10000, notification.build());
}