Example usage for android.text.style ForegroundColorSpan ForegroundColorSpan

List of usage examples for android.text.style ForegroundColorSpan ForegroundColorSpan

Introduction

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

Prototype

public ForegroundColorSpan(@NonNull Parcel src) 

Source Link

Document

Creates a ForegroundColorSpan from a parcel.

Usage

From source file:com.air.mobilebrowser.BrowserActivity.java

/** Logs an onscreen message for debugging. */
public void logMessage(final TextView consoleView, String message, String value, int color) {
    if (mIsDebugEnabled && consoleView != null) {
        consoleView.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override//  www . j ava  2s.c  om
            public void onFocusChange(View v, boolean hasFocus) {

                ViewParent parent = consoleView.getParent();
                final ScrollView scroll = (ScrollView) parent;

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {

                        scroll.smoothScrollTo(0, consoleView.getMeasuredHeight() + 10);

                    }
                }, 0);

            }
        });
        Editable editable = consoleView.getEditableText();

        SpannableString str = null;

        if (editable == null) {
            editable = new SpannableStringBuilder();
            str = new SpannableString(message + ": " + value);
            str.setSpan(new ForegroundColorSpan(color), message.length() + 2,
                    message.length() + 2 + value.length(), 0);
        } else {
            str = new SpannableString("\n" + message + ": " + value);
            str.setSpan(new ForegroundColorSpan(color), message.length() + 2,
                    message.length() + 3 + value.length(), 0);
        }

        editable.append(str);

        consoleView.setText(editable, TextView.BufferType.EDITABLE);

        ViewParent parent = consoleView.getParent();
        if (parent instanceof ScrollView) {
            final ScrollView scroll = (ScrollView) parent;

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    scroll.smoothScrollTo(0, consoleView.getMeasuredHeight() + 10);

                }
            }, 1000);
        }
    }
}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

private CharSequence generateFastForwardOrRewindTxt(long changingTime) {

    long duration = player == null ? 0 : player.getDuration();
    String result = stringForTime(changingTime) + " / " + stringForTime(duration);

    int index = result.indexOf("/");

    SpannableString spannableString = new SpannableString(result);

    TypedValue typedValue = new TypedValue();
    TypedArray a = getContext().obtainStyledAttributes(typedValue.data, new int[] { R.attr.colorAccent });
    int color = a.getColor(0, 0);
    a.recycle();/*from   www.  j av  a2 s .co m*/
    spannableString.setSpan(new ForegroundColorSpan(color), 0, index, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    return spannableString;
}

From source file:hku.fyp14017.blencode.ui.fragment.LookFragment.java

private void updateActionModeTitle() {
    int numberOfSelectedItems = adapter.getAmountOfCheckedItems();

    if (numberOfSelectedItems == 0) {
        actionMode.setTitle(actionModeTitle);
    } else {//  www . j  a  va  2 s.co m
        String appendix = multipleItemAppendixActionMode;

        if (numberOfSelectedItems == 1) {
            appendix = singleItemAppendixActionMode;
        }

        String numberOfItems = Integer.toString(numberOfSelectedItems);
        String completeTitle = actionModeTitle + " " + numberOfItems + " " + appendix;

        int titleLength = actionModeTitle.length();

        Spannable completeSpannedTitle = new SpannableString(completeTitle);
        completeSpannedTitle.setSpan(
                new ForegroundColorSpan(
                        getResources().getColor(hku.fyp14017.blencode.R.color.actionbar_title_color)),
                titleLength + 1, titleLength + (1 + numberOfItems.length()),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        actionMode.setTitle(completeSpannedTitle);
    }
}

From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    MenuItem item = menu.add(Menu.NONE, ACTIONBAR_MENU_ITEM_FIILTER, Menu.NONE,
            getString(R.string.order_call_taxi_page_title));
    SpannableString spanString = new SpannableString(item.getTitle().toString());
    spanString.setSpan(new ForegroundColorSpan(Color.WHITE), 0, spanString.length(), 0); //fix the color to white
    item.setTitle(spanString);// w w w .  ja  va 2s . c om
    if (isShowOneKey)
        item.setVisible(true);
    else
        item.setVisible(false);
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    super.onCreateOptionsMenu(menu, inflater);
}

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

public static ParsedMessage formatMessageText(final Context ctx, final JuickMessage jmsg, boolean condensed) {
    if (jmsg.parsedText != null) {
        return (ParsedMessage) jmsg.parsedText; // was parsed before
    }/*  ww  w.j  a v a 2  s  .  com*/
    getColorTheme(ctx);
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    int spanOffset = 0;
    final boolean isMainMessage = jmsg.getRID() == 0;
    final boolean doCompactComment = !isMainMessage && compactComments;
    if (jmsg.continuationInformation != null) {
        ssb.append(jmsg.continuationInformation + "\n");
        ssb.setSpan(new StyleSpan(Typeface.ITALIC), spanOffset, ssb.length() - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    //
    // NAME
    //
    spanOffset = ssb.length();
    String name = '@' + jmsg.User.UName;
    int userNameStart = ssb.length();
    ssb.append(name);
    int userNameEnd = ssb.length();
    StyleSpan userNameBoldSpan;
    ForegroundColorSpan userNameColorSpan;
    ssb.setSpan(userNameBoldSpan = new StyleSpan(Typeface.BOLD), spanOffset, ssb.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.setSpan(
            userNameColorSpan = new ForegroundColorSpan(
                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME, 0xFFC8934E)),
            spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNueBold), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    ssb.append(' ');
    spanOffset = ssb.length();

    if (!condensed) {
        //
        // TAGS
        //
        String tags = jmsg.getTags();
        if (feedlyFonts)
            tags = tags.toUpperCase();
        ssb.append(tags + "\n");
        if (tags.length() > 0) {
            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TAGS, 0xFF0000CC)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (feedlyFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.dinWebPro), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (helvNueFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

        }
        spanOffset = ssb.length();
    }
    if (jmsg.translated) {
        //
        // 'translated'
        //
        ssb.append("translated: ");
        ssb.setSpan(
                new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    int bodyOffset = ssb.length();
    int messageNumberStart = -1, messageNumberEnd = -1;
    if (showNumbers(ctx) && !condensed) {
        //
        // numbers
        //
        if (isMainMessage) {
            messageNumberStart = ssb.length();
            ssb.append(jmsg.getDisplayMessageNo());
            messageNumberEnd = ssb.length();
        } else {
            ssb.append("/" + jmsg.getRID());
            if (jmsg.getReplyTo() != 0) {
                ssb.append("->" + jmsg.getReplyTo());
            }
        }
        ssb.append(" ");
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.MESSAGE_ID, 0xFFa0a5bd)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    //
    // MESSAGE BODY
    //
    String txt = Censor.getCensoredText(jmsg.Text);
    if (!condensed) {
        if (jmsg.Photo != null) {
            txt = jmsg.Photo + "\n" + txt;
        }
        if (jmsg.Video != null) {
            txt = jmsg.Video + "\n" + txt;
        }
    }
    ssb.append(txt);
    boolean ssbChanged = false; // allocation optimization
    // Highlight links http://example.com/
    ArrayList<ExtractURLFromMessage.FoundURL> foundURLs = ExtractURLFromMessage.extractUrls(txt, jmsg.getMID());
    ArrayList<String> urls = new ArrayList<String>();
    for (ExtractURLFromMessage.FoundURL foundURL : foundURLs) {
        setSSBSpan(ssb, new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + foundURL.start, spanOffset + foundURL.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        urls.add(foundURL.url);
        if (foundURL.title != null) {
            ssb.replace(spanOffset + foundURL.title.start - 1, spanOffset + foundURL.title.start, " ");
            ssb.replace(spanOffset + foundURL.title.end, spanOffset + foundURL.title.end + 1, " ");
            ssb.replace(spanOffset + foundURL.start - 1, spanOffset + foundURL.start, "(");
            ssb.replace(spanOffset + foundURL.end, spanOffset + foundURL.end + 1, ")");
            ssb.setSpan(new StyleSpan(Typeface.BOLD), spanOffset + foundURL.title.start,
                    spanOffset + foundURL.title.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        ssbChanged = true;
    }
    // bold italic underline
    if (jmsg.Text.indexOf("*") != -1) {
        setStyleSpans(ssb, spanOffset, Typeface.BOLD, "*");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("/") != 0) {
        setStyleSpans(ssb, spanOffset, Typeface.ITALIC, "/");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("_") != 0) {
        setStyleSpans(ssb, spanOffset, UnderlineSpan.class, "_");
        ssbChanged = true;
    }
    if (ssbChanged) {
        txt = ssb.subSequence(spanOffset, ssb.length()).toString(); // ssb was modified in between
    }

    // Highlight nick
    String accountName = XMPPService.getMyAccountName(jmsg.getMID(), ctx);
    if (accountName != null) {
        int scan = spanOffset;
        String nickScanArea = (ssb + " ").toUpperCase();
        while (true) {
            int myNick = nickScanArea.indexOf("@" + accountName.toUpperCase(), scan);
            if (myNick != -1) {
                if (!isNickPart(nickScanArea.charAt(myNick + accountName.length() + 1))) {
                    setSSBSpan(ssb,
                            new BackgroundColorSpan(
                                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME_ME, 0xFF938e00)),
                            myNick - 1, myNick + accountName.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                scan = myNick + 1;
            } else {
                break;
            }
        }
    }

    // Highlight messages #1234
    int pos = 0;
    Matcher m = getCrossReferenceMsgPattern(jmsg.getMID()).matcher(txt);
    while (m.find(pos)) {
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + m.start(), spanOffset + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        pos = m.end();
    }

    SpannableStringBuilder compactDt = null;
    if (!condensed) {

        // found messages count (search results)
        if (jmsg.myFoundCount != 0 || jmsg.hisFoundCount != 0) {
            ssb.append("\n");
            int where = ssb.length();
            if (jmsg.myFoundCount != 0) {
                ssb.append(ctx.getString(R.string.MyReplies_) + jmsg.myFoundCount + "  ");
            }
            if (jmsg.hisFoundCount != 0) {
                ssb.append(ctx.getString(R.string.UserReplies_) + jmsg.hisFoundCount);
            }
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                    where, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        int rightPartOffset = spanOffset = ssb.length();

        if (!doCompactComment) {
            //
            // TIME (bottom of message)
            //

            try {
                DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                if (date.endsWith("/76"))
                    date = date.substring(0, date.length() - 3); // special case for no year in datasource
                ssb.append("\n" + date + " ");
            } catch (Exception e) {
                ssb.append("\n[fmt err] ");
            }

            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            compactDt = new SpannableStringBuilder();
            try {
                if (true || jmsg.deltaTime != Long.MIN_VALUE) {
                    compactDt.append(com.juickadvanced.Utils.toRelaviteDate(jmsg.Timestamp.getTime(), russian));
                } else {
                    DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                    String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                    if (date.endsWith("/76"))
                        date = date.substring(0, date.length() - 3); // special case for no year in datasource
                    compactDt.append(date);
                }
            } catch (Exception e) {
                compactDt.append("\n[fmt err] ");
            }
            compactDt.setSpan(
                    new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)), 0,
                    compactDt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        spanOffset = ssb.length();

        //
        // Number of REPLIES
        //
        if (jmsg.replies > 0) {
            String replies = Replies + jmsg.replies;
            ssb.append(" " + replies);
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.NUMBER_OF_COMMENTS, 0xFFC8934E)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new WrapTogetherSpan() {
            }, spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!doCompactComment) {
            // right align
            ssb.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), rightPartOffset, ssb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), bodyOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    LeadingMarginSpan.LeadingMarginSpan2 userpicSpan = null;
    if (showUserpics(ctx) && !condensed) {
        userpicSpan = new LeadingMarginSpan.LeadingMarginSpan2() {
            @Override
            public int getLeadingMarginLineCount() {
                if (_wrapUserpics) {
                    return 2;
                } else {
                    return 22222;
                }
            }

            @Override
            public int getLeadingMargin(boolean first) {
                if (first) {
                    return (int) (2 * getLineHeight(ctx, (double) textScale));
                } else {
                    return 0;
                }
            }

            @Override
            public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
                    CharSequence text, int start, int end, boolean first, Layout layout) {
            }
        };
        ssb.setSpan(userpicSpan, 0, ssb.length(), 0);
    }
    ParsedMessage parsedMessage = new ParsedMessage(ssb, urls);
    parsedMessage.userpicSpan = userpicSpan;
    parsedMessage.userNameBoldSpan = userNameBoldSpan;
    parsedMessage.userNameColorSpan = userNameColorSpan;
    parsedMessage.userNameStart = userNameStart;
    parsedMessage.userNameEnd = userNameEnd;
    parsedMessage.messageNumberStart = messageNumberStart;
    parsedMessage.messageNumberEnd = messageNumberEnd;
    parsedMessage.compactDate = compactDt;
    return parsedMessage;
}

From source file:com.andrewshu.android.reddit.comments.CommentsListActivity.java

/**
 * Mark the OP submitter comments/*from ww w . ja v  a2 s . com*/
 */
void markSubmitterComments() {
    if (getOpThingInfo() == null || mCommentsAdapter == null)
        return;

    SpannableString authorSS = new SpannableString(getOpThingInfo().getAuthor() + " [S]");
    ForegroundColorSpan fcs;
    if (Util.isLightTheme(mSettings.getTheme()))
        fcs = new ForegroundColorSpan(getResources().getColor(R.color.blue));
    else
        fcs = new ForegroundColorSpan(getResources().getColor(R.color.pale_blue));
    authorSS.setSpan(fcs, 0, authorSS.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    for (int i = 0; i < mCommentsAdapter.getCount(); i++) {
        ThingInfo ci = mCommentsAdapter.getItem(i);
        // if it's the OP, mark his name
        if (getOpThingInfo().getAuthor().equalsIgnoreCase(ci.getAuthor()))
            ci.setSSAuthor(authorSS);
    }
}

From source file:org.catrobat.catroid.ui.fragment.LookFragment.java

private void updateActionModeTitle() {
    int numberOfSelectedItems = adapter.getAmountOfCheckedItems();

    if (numberOfSelectedItems == 0) {
        actionMode.setTitle(actionModeTitle);
    } else {/*from  ww  w . j  a v a2s  . com*/
        String appendix = multipleItemAppendixActionMode;

        if (numberOfSelectedItems == 1) {
            appendix = singleItemAppendixActionMode;
        }

        String numberOfItems = Integer.toString(numberOfSelectedItems);
        String completeTitle = actionModeTitle + " " + numberOfItems + " " + appendix;

        int titleLength = actionModeTitle.length();

        Spannable completeSpannedTitle = new SpannableString(completeTitle);
        completeSpannedTitle.setSpan(
                new ForegroundColorSpan(getResources().getColor(R.color.actionbar_title_color)),
                titleLength + 1, titleLength + (1 + numberOfItems.length()),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        actionMode.setTitle(completeSpannedTitle);
    }
}

From source file:com.nttec.everychan.ui.presentation.HtmlParser.java

private static void endFont(SpannableStringBuilder text) {
    int len = text.length();
    Object obj = getLast(text, Font.class);
    int where = text.getSpanStart(obj);

    text.removeSpan(obj);//from w w w.j  ava  2s. co m

    if (where != len) {
        Font f = (Font) obj;

        if (!TextUtils.isEmpty(f.mColor)) {
            if (f.mColor.startsWith("@")) {
                Resources res = Resources.getSystem();
                String name = f.mColor.substring(1);
                int colorRes = res.getIdentifier(name, "color", "android");
                if (colorRes != 0) {
                    ColorStateList colors = CompatibilityUtils.getColorStateList(res, colorRes);
                    text.setSpan(new TextAppearanceSpan(null, 0, 0, colors, null), where, len,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            } else {
                int c = ColorHidden.getHtmlColor(f.mColor);
                if (c != -1) {
                    text.setSpan(new ForegroundColorSpan(c | 0xFF000000), where, len,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }

        if (f.mFace != null) {
            text.setSpan(new TypefaceSpan(f.mFace), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        if (f.mStyle != null) {
            List<Object> styleSpans = parseStyleAttributes(f.mStyle);
            for (Object span : styleSpans) {
                text.setSpan(span, where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
}

From source file:com.forrestguice.suntimeswidget.SuntimesUtils.java

public static SpannableString createColorSpan(String text, String toColorize, int color) {
    SpannableString span = new SpannableString(text);
    int start = text.indexOf(toColorize);
    int end = start + toColorize.length();
    span.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return span;//from  ww w.  j av  a  2s  .  com
}

From source file:com.sina.weibo.sdk.demo.sample.activity.TestFragment.java

public SpannableStringBuilder setTextColor(String str) {
    // ????????/*  w w  w  .ja v a2s .  c om*/
    int bstart = 0;
    int bend = 0;
    int fstart = 0;
    int fend = 0;
    int a = 0;
    int b = 0;
    int c = 0;
    SpannableStringBuilder style = new SpannableStringBuilder(str);
    while (true) {
        bstart = str.indexOf("@", bend);
        a = str.indexOf(" ", bstart);
        c = str.indexOf(":", bstart);
        a = a < c ? a : c;
        if (bstart < 0) {
            break;
        } else {
            if (a < 0) {
                break;
            } else {
                bend = a;
            }
            style.setSpan(new ForegroundColorSpan(0xFF0099ff), bstart, a, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
    }
    while (true) {
        fstart = str.indexOf("#", fend);
        b = str.indexOf("#", fstart + 1);
        if (fstart < 0) {
            break;
        } else {
            if (b < 0) {
                break;
            } else {
                fend = b + 1;
            }
            style.setSpan(new ForegroundColorSpan(0xFF0099ff), fstart, fend,
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
    }
    return style;
}