Java 类android.text.SpannableString 实例源码

项目:IslamicLibraryAndroid    文件:SearchResult.java   
public CharSequence getformatedSearchSnippet() {
    //TODO implement improved snippet function
    String CleanedSearchString = " " + ArabicUtilities.cleanTextForSearchingWthStingBuilder(searchString) + " ";
    StringBuilder cleanedUnformattedPage = new StringBuilder(ArabicUtilities.cleanTextForSearchingWthStingBuilder(unformatedPage));
    int firstMatchStart = cleanedUnformattedPage.indexOf(CleanedSearchString);
    cleanedUnformattedPage.delete(0, Math.max(firstMatchStart - 100, 0));
    cleanedUnformattedPage.delete(
            Math.min(firstMatchStart + CleanedSearchString.length() + 100, cleanedUnformattedPage.length())
            , cleanedUnformattedPage.length());
    cleanedUnformattedPage.insert(0, "...");
    cleanedUnformattedPage.append("...");

    Spannable snippet = SpannableString.
            valueOf(cleanedUnformattedPage.toString());
    int index = TextUtils.indexOf(snippet, CleanedSearchString);
    while (index >= 0) {

        snippet.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
                + CleanedSearchString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        index = TextUtils.indexOf(snippet, CleanedSearchString, index + CleanedSearchString.length());
    }

    return snippet;
}
项目:Nird2    文件:UiUtils.java   
public static SpannableStringBuilder getTeaser(Context ctx, Spanned body) {
    if (body.length() < TEASER_LENGTH)
        throw new IllegalArgumentException(
                "String is shorter than TEASER_LENGTH");

    SpannableStringBuilder builder =
            new SpannableStringBuilder(body.subSequence(0, TEASER_LENGTH));
    String ellipsis = ctx.getString(R.string.ellipsis);
    builder.append(ellipsis).append(" ");

    Spannable readMore = new SpannableString(
            ctx.getString(R.string.read_more) + ellipsis);
    ForegroundColorSpan fg = new ForegroundColorSpan(
            ContextCompat.getColor(ctx, R.color.briar_text_link));
    readMore.setSpan(fg, 0, readMore.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(readMore);

    return builder;
}
项目:AgentWeb    文件:AgentWebUtils.java   
static void show(View parent,
                 CharSequence text,
                 int duration,
                 @ColorInt int textColor,
                 @ColorInt int bgColor,
                 CharSequence actionText,
                 @ColorInt int actionTextColor,
                 View.OnClickListener listener) {
    SpannableString spannableString = new SpannableString(text);
    ForegroundColorSpan colorSpan = new ForegroundColorSpan(textColor);
    spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    snackbarWeakReference = new WeakReference<>(Snackbar.make(parent, spannableString, duration));
    Snackbar snackbar = snackbarWeakReference.get();
    View view = snackbar.getView();
    view.setBackgroundColor(bgColor);
    if (actionText != null && actionText.length() > 0 && listener != null) {
        snackbar.setActionTextColor(actionTextColor);
        snackbar.setAction(actionText, listener);
    }
    snackbar.show();

}
项目:GitHub    文件:BookMarkAdapter.java   
@Override
public void convert(EasyLVHolder holder, int position, BookMark item) {
    TextView tv = holder.getView(R.id.tvMarkItem);

    SpannableString spanText = new SpannableString((position + 1) + ". " + item.title + ": ");
    spanText.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.light_coffee)),
            0, spanText.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

    tv.setText(spanText);

    if (item.desc != null) {
        tv.append(item.desc
                .replaceAll(" ", "")
                .replaceAll(" ", "")
                .replaceAll("\n", ""));
    }

}
项目:PocketGopher    文件:UnknownPage.java   
public void render(final TextView textView, final Context context, String line)
{
    final Handler handler = new Handler(Looper.getMainLooper());
    final SpannableString text = new SpannableString("  " + line + "\n");

    handler.post(new Runnable()
    {
        @Override
        public void run()
        {
            //set the image tag behind (left of) the text
            text.setSpan(new ImageSpan(context, IMAGE_TAG), 0, 1, 0);
            textView.append(text);
        }
    });
}
项目:revolution-irc    文件:UserAutoRunCommandHelper.java   
@Override
public void showDialog(Activity activity) {
    super.showDialog(activity);
    dismissDialog(activity);
    ThemedAlertDialog.Builder dialog = new ThemedAlertDialog.Builder(activity);
    dialog.setTitle(R.string.connection_error_command_title);

    StringBuilder commands = new StringBuilder();
    for (String cmd : mCommands) {
        commands.append('/');
        commands.append(cmd);
        commands.append('\n');
    }
    SpannableString commandsSeq = new SpannableString(commands);
    commandsSeq.setSpan(new TypefaceSpan("monospace"), 0, commandsSeq.length(),
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    dialog.setMessage(SpannableStringHelper.format(activity.getResources().getQuantityText(
            R.plurals.connection_error_command_dialog_content, mCommands.size()),
            mNetworkName, commandsSeq));
    dialog.setPositiveButton(R.string.action_ok, null);
    dialog.setOnDismissListener((DialogInterface di) -> {
        dismiss();
    });
    mDialog = dialog.show();
}
项目:Tusky    文件:MentionTokenizer.java   
@Override
public CharSequence terminateToken(CharSequence text) {
    int i = text.length();
    while (i > 0 && text.charAt(i - 1) == ' ') {
        i--;
    }
    if (i > 0 && text.charAt(i - 1) == ' ') {
        return text;
    } else if (text instanceof Spanned) {
        SpannableString s = new SpannableString(text + " ");
        TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, s, 0);
        return s;
    } else {
        return text + " ";
    }
}
项目:AndroidUtilCode-master    文件:SnackbarUtils.java   
/**
 * 设置snackbar文字和背景颜色
 *
 * @param parent          父视图(CoordinatorLayout或者DecorView)
 * @param text            文本
 * @param duration        显示时长
 * @param textColor       文本颜色
 * @param bgColor         背景色
 * @param actionText      事件文本
 * @param actionTextColor 事件文本颜色
 * @param listener        监听器
 */
private static void show(View parent,
                         CharSequence text,
                         int duration,
                         @ColorInt int textColor,
                         @ColorInt int bgColor,
                         CharSequence actionText,
                         @ColorInt int actionTextColor,
                         View.OnClickListener listener) {
    SpannableString spannableString = new SpannableString(text);
    ForegroundColorSpan colorSpan = new ForegroundColorSpan(textColor);
    spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    snackbarWeakReference = new WeakReference<>(Snackbar.make(parent, spannableString, duration));
    Snackbar snackbar = snackbarWeakReference.get();
    View view = snackbar.getView();
    view.setBackgroundColor(bgColor);
    if (actionText != null && actionText.length() > 0 && listener != null) {
        snackbar.setActionTextColor(actionTextColor);
        snackbar.setAction(actionText, listener);
    }
    snackbar.show();
}
项目:Quizca-UI-Concept    文件:MainActivity.java   
public SpannableString getDesignationText()
{
    String text = txtDesignation.getText().toString();

    SpannableString s = new SpannableString(text);

    s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)), text.indexOf("@"), text.length(), 0);

    /*
    s.setSpan(new RelativeSizeSpan(1.2f), text.indexOf("A"), text.length(), 0);
    s.setSpan(new StyleSpan(Typeface.NORMAL), text.indexOf("A"), text.length(), 0);
    s.setSpan(new ForegroundColorSpan(Color.BLACK), text.indexOf("A"), text.length(), 0);
    */

    return s;
}
项目:SimpleDialogFragments    文件:MainActivity.java   
private void newColor(int color){
    this.color = color;

    // Sets action bar colors
    if (getSupportActionBar() == null) return;

    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xFF000000 | color));

    boolean dark = Color.red(color) * 0.299 + Color.green(color) * 0.587 + Color.blue(color) * 0.114 < 180;
    SpannableString s = new SpannableString(getSupportActionBar().getTitle());
    s.setSpan(new ForegroundColorSpan(dark ? Color.WHITE : Color.BLACK), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    getSupportActionBar().setTitle(s);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        hsv[2] *= 0.75;
        getWindow().setStatusBarColor(Color.HSVToColor(hsv));
    }
}
项目:ultrasonic    文件:SelectPlaylistActivity.java   
private void displayPlaylistInfo(final Playlist playlist)
{
    final TextView textView = new TextView(this);
    textView.setPadding(5, 5, 5, 5);

    final Spannable message = new SpannableString("Owner: " + playlist.getOwner() + "\nComments: " +
            ((playlist.getComment() == null) ? "" : playlist.getComment()) +
            "\nSong Count: " + playlist.getSongCount() +
            ((playlist.getPublic() == null) ? "" : ("\nPublic: " + playlist.getPublic()) + ((playlist.getCreated() == null) ? "" : ("\nCreation Date: " + playlist.getCreated().replace('T', ' ')))));

    Linkify.addLinks(message, Linkify.WEB_URLS);
    textView.setText(message);
    textView.setMovementMethod(LinkMovementMethod.getInstance());

    new AlertDialog.Builder(this).setTitle(playlist.getName()).setCancelable(true).setIcon(android.R.drawable.ic_dialog_info).setView(textView).show();
}
项目:ChenYan    文件:Main2Activity.java   
private void spanTest() {
        SpannableString spannableString = new SpannableString("欢迎光临我的博客");
//        字体颜色span
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.BLUE);
//        背景颜色span
        BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.RED);

//        1,3其实是两个位置,末尾不包括
//        Flag 为 span如果新增了文字 的前面不包括样式,后面包括样式
        spannableString.setSpan(colorSpan, 1, 3, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableString.setSpan(backgroundColorSpan, 5, 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(spannableString);

        editText.setText(spannableString);

    }
项目:TextReader    文件:BookContentTextView.java   
public void setText(String text) {
    int startIndex = 0;
    while (true) {

        int start = text.indexOf("《");
        int end = text.indexOf("》");
        if (start < 0 || end < 0) {
            append(text.substring(startIndex));
            break;
        }

        append(text.substring(startIndex, start));

        SpannableString spanableInfo = new SpannableString(text.substring(start, end + 1));
        spanableInfo.setSpan(new Clickable(spanableInfo.toString()), 0, end + 1 - start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        append(spanableInfo);
        //setMovementMethod()该方法必须调用,否则点击事件不响应
        setMovementMethod(LinkMovementMethod.getInstance());
        text = text.substring(end + 1);

        LogUtils.e(spanableInfo.toString());
    }
}
项目:PeSanKita-android    文件:ComposeText.java   
public void setHint(@NonNull String hint, @Nullable CharSequence subHint) {
  this.hint = new SpannableString(hint);
  this.hint.setSpan(new RelativeSizeSpan(0.8f), 0, hint.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

  if (subHint != null) {
    this.subHint = new SpannableString(subHint);
    this.subHint.setSpan(new RelativeSizeSpan(0.8f), 0, subHint.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  } else {
    this.subHint = null;
  }

  if (this.subHint != null) {
    super.setHint(new SpannableStringBuilder().append(ellipsizeToWidth(this.hint))
                                              .append("\n")
                                              .append(ellipsizeToWidth(this.subHint)));
  } else {
    super.setHint(ellipsizeToWidth(this.hint));
  }
}
项目:orgzly-android    文件:TitleGenerator.java   
private CharSequence generateState(OrgHead head) {
    SpannableString str = new SpannableString(head.getState());

    ForegroundColorSpan color;

    if (AppPreferences.todoKeywordsSet(mContext).contains(head.getState())) {
        color = attributes.colorTodo;
    } else if (AppPreferences.doneKeywordsSet(mContext).contains(head.getState())) {
        color = attributes.colorDone;
    } else {
        color = attributes.colorUnknown;
    }

    str.setSpan(color, 0, str.length(), 0);

    return str;
}
项目:yyox    文件:OrderDetailActivity.java   
@Override
    public void setFeeValue(Fee fee) {
        if (fee != null || 1 == getIntent().getIntExtra("type", OrderStatus.ORDER_STATUS_DETAIL)) {
            totalAmount = fee.getMoney().getTotalAmount();
            if (mOrderDetail.getCouponList() == null || mOrderDetail.getCouponList().getCoupon() == null || mOrderDetail.getCouponList().getCoupon().getName().equals("")) {
                mTextView_Coupon_Value.setText("有" + fee.getCouponNumber() + "张可用");
            }
//            mTextView_Fee.setText("运费:" + CommonUtils.doubleFormat(fee.getMoney().getTotalAmount()));

            SpannableString styledText = new SpannableString("运费:¥"+CommonUtils.doubleFormat(fee.getMoney().getTotalAmount()));
            int color = getResources().getColor(R.color.my_yellow);
            styledText.setSpan(new ForegroundColorSpan(color), 0, 3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            mTextView_Fee.setText(styledText);

            mOrderDetail.setValueAddedlist(fee.getValueAddedlist());
            this.fee = fee.getMoney().getTotalAmount();
        }
    }
项目:MultiContactPicker    文件:MultiContactPickerAdapter.java   
private void highlightTerm(TextView tv, String query, String originalString){
    if (query != null && !query.isEmpty()) {
        int startPos = originalString.toLowerCase().indexOf(query.toLowerCase());
        int endPos = startPos + query.length();
        if (startPos != -1) {
            Spannable spannable = new SpannableString(originalString);
            ColorStateList blackColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLACK});
            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blackColor, null);
            spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(spannable);
        } else {
            tv.setText(originalString);
        }
    } else {
        tv.setText(originalString);
    }
}
项目:orgzly-android    文件:SpaceTokenizer.java   
@Override
public CharSequence terminateToken(CharSequence text) {
    int i = text.length();

    while (i > 0 && text.charAt(i - 1) == ' ') {
        i--;
    }

    if (i > 0 && text.charAt(i - 1) == ' ') {
        return text;
    } else {
        if (text instanceof Spanned) {
            SpannableString sp = new SpannableString(text + " ");
            TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
                    Object.class, sp, 0);
            return sp;
        } else {
            return text + " ";
        }
    }
}
项目:QueryHighlighter    文件:QueryHighlighter.java   
public CharSequence apply(CharSequence text, CharSequence wordPrefix) {
    final CharSequence normalizedText = mQueryNormalizer.normalize(text);
    final CharSequence normalizedWordPrefix = mQueryNormalizer.normalize(wordPrefix);

    final int index = indexOfQuery(normalizedText, normalizedWordPrefix);
    if (index != -1) {
        final SpannableString result = new SpannableString(text);
        result.setSpan(mHighlightStyle, index, index + normalizedWordPrefix.length(), 0);
        return result;
    } else {
        return text;
    }
}
项目:RetrofitSample    文件:DlEmptyLayout.java   
private void setEmptyTv(TextView textView, String tipStr, String clickStr) {
    if (!TextUtils.isEmpty(clickStr)) {
        SpannableString spStr = new SpannableString(tipStr + clickStr);
        mClickableSpan = new CustomizedClickableSpan(R.color.new_bg, getContext().getApplicationContext(), mOnClickListener);
        spStr.setSpan(mClickableSpan, tipStr.length(), tipStr.length() + clickStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        textView.setText(spStr);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    } else {
        textView.setText(tipStr);
    }
}
项目:GongXianSheng    文件:DateFormateUtil.java   
public static SpannableString formatData(String time) {
    if ( TextUtils.isEmpty(time) ) {
        return null;
    }
    // 24小时内:几分钟前。。。,超过24小时:4月11日 20:20, 历史年份:2014年4月12日;
    final Calendar calend = dateFormatFromString(time,
            DateFormateUtil.FORMAT_FULL_DATE_TIME_WITH_SYMBOL);
    if (isToday(calend)) {
        SpannableString ss = new SpannableString("今天");
        ss.setSpan(new AbsoluteSizeSpan(18,true),0,ss.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return ss;
    }
    else if (isYesterday(calend)) {
        SpannableString yy = new SpannableString("昨天");
        yy.setSpan(new AbsoluteSizeSpan(18,true),0,yy.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return yy;
    }
    else {
        int day = calend.get(Calendar.DAY_OF_MONTH);
        String datStr = String.format("%02d",day);
        int month = calend.get(Calendar.MONTH)+1;
        String monthStr = getMonthForStr(month);
        SpannableString spannableString = new SpannableString(datStr+"\n"+monthStr);
        spannableString.setSpan(new AbsoluteSizeSpan(20,true),0,datStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new AbsoluteSizeSpan(16,true),datStr.length()+1,spannableString.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }
}
项目:Aurora    文件:UiUtils.java   
/**
 * 设置hint大小
 *
 * @param size
 * @param v
 * @param res
 */
public static void setViewHintSize(Context context, int size, TextView v, int res) {
    SpannableString ss = new SpannableString(getResources(context).getString(
            res));
    // 新建一个属性对象,设置文字的大小
    AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);
    // 附加属性到文本  
    ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // 设置hint  
    v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
}
项目:yjPlay    文件:GestureVideoPlayer.java   
/****
 * 滑动进度
 *
 * @param  seekTimePosition  滑动的时间
 * @param  duration         视频总长
 * @param  seekTime    滑动的时间 格式化00:00
 * @param  totalTime    视频总长 格式化00:00
 **/
private void showProgressDialog(long seekTimePosition, long duration, String seekTime, String totalTime) {
    newPosition = seekTimePosition;
    if (onGestureProgressListener != null) {
        onGestureProgressListener.showProgressDialog(seekTimePosition, duration, seekTime, totalTime);
    } else {
        String stringBuilder = seekTime + "/" + totalTime;
        ForegroundColorSpan blueSpan = new ForegroundColorSpan(ContextCompat.getColor(activity, R.color.simple_exo_style_color));
        SpannableString spannableString = new SpannableString(stringBuilder);
        spannableString.setSpan(blueSpan, 0, seekTime.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        getPlayerViewListener().setTimePosition(spannableString);
    }
}
项目:q-mail    文件:ICalendarHelper.java   
@VisibleForTesting
static CharSequence toFriendly(Attendee attendee, Contacts contacts,
                               boolean showCorrespondentNames,
                               boolean changeContactNameColor,
                               int contactNameColor) {
    if (!showCorrespondentNames) {
        return attendee.getEmail();
    } else if (contacts != null) {
        final String name = contacts.getNameForAddress(attendee.getEmail());
        // TODO: The results should probably be cached for performance reasons.
        if (name != null) {
            if (changeContactNameColor) {
                final SpannableString coloredName = new SpannableString(name);
                coloredName.setSpan(new ForegroundColorSpan(contactNameColor),
                        0,
                        coloredName.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
                return coloredName;
            } else {
                return name;
            }
        }
    }

    return (!TextUtils.isEmpty(attendee.getCommonName())) ? attendee.getCommonName() : attendee.getEmail();
}
项目:q-mail    文件:ICalendarHelper.java   
@VisibleForTesting
static CharSequence toFriendly(Organizer organizer, Contacts contacts,
                               boolean showCorrespondentNames,
                               boolean changeContactNameColor,
                               int contactNameColor) {
    if (organizer == null) {
        return null;
    }
    if (!showCorrespondentNames) {
        return organizer.getEmail();
    } else if (contacts != null) {
        final String name = contacts.getNameForAddress(organizer.getEmail());
        // TODO: The results should probably be cached for performance reasons.
        if (name != null) {
            if (changeContactNameColor) {
                final SpannableString coloredName = new SpannableString(name);
                coloredName.setSpan(new ForegroundColorSpan(contactNameColor),
                        0,
                        coloredName.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
                return coloredName;
            } else {
                return name;
            }
        }
    }

    return (!TextUtils.isEmpty(organizer.getCommonName())) ? organizer.getCommonName() : organizer.getEmail();
}
项目:q-mail    文件:MessageHelper.java   
@VisibleForTesting
/* package, for testing */ static CharSequence toFriendly(Address address, Contacts contacts,
                                             boolean showCorrespondentNames,
                                             boolean changeContactNameColor,
                                             int contactNameColor) {
    if (!showCorrespondentNames) {
        return address.getAddress();
    } else if (contacts != null) {
        final String name = contacts.getNameForAddress(address.getAddress());
        // TODO: The results should probably be cached for performance reasons.
        if (name != null) {
            if (changeContactNameColor) {
                final SpannableString coloredName = new SpannableString(name);
                coloredName.setSpan(new ForegroundColorSpan(contactNameColor),
                        0,
                        coloredName.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
                return coloredName;
            } else {
                return name;
            }
        }
    }

    return (!TextUtils.isEmpty(address.getPersonal())) ? address.getPersonal() : address.getAddress();
}
项目:NeiHanDuanZiTV    文件:ArmsUtils.java   
/**
 * 设置hint大小
 *
 * @param size
 * @param v
 * @param res
 */
public static void setViewHintSize(Context context, int size, TextView v, int res) {
    SpannableString ss = new SpannableString(getResources(context).getString(
            res));
    // 新建一个属性对象,设置文字的大小
    AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);
    // 附加属性到文本  
    ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // 设置hint  
    v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
}
项目:GitHub    文件:PiePolylineChartActivity.java   
private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.5f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.65f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }
项目:FastLib    文件:SnackBarUtil.java   
/**
 * 显示SnackBar
 */
public void show() {
    final View view = parent.get();
    if (view == null) return;
    if (messageColor != DEFAULT_COLOR) {
        SpannableString spannableString = new SpannableString(message);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(messageColor);
        spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mWeakReference = new WeakReference<>(Snackbar.make(view, spannableString, duration));
    } else {
        mWeakReference = new WeakReference<>(Snackbar.make(view, message, duration));
    }
    final Snackbar snackbar = mWeakReference.get();
    final View snackView = snackbar.getView();
    if (bgResource != -1) {
        snackView.setBackgroundResource(bgResource);
    } else if (bgColor != DEFAULT_COLOR) {
        snackView.setBackgroundColor(bgColor);
    }
    if (bottomMargin != 0) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) snackView.getLayoutParams();
        params.bottomMargin = bottomMargin;
    }
    if (actionText.length() > 0 && actionListener != null) {
        if (actionTextColor != DEFAULT_COLOR) {
            snackbar.setActionTextColor(actionTextColor);
        }
        snackbar.setAction(actionText, actionListener);
    }
    snackbar.show();
}
项目:Cable-Android    文件:ContactSelectionListAdapter.java   
private CharSequence getSpannedHeaderString(int position) {
  final String headerString = getHeaderString(position);
  if (isPush(position)) {
    SpannableString spannable = new SpannableString(headerString);
    spannable.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.signal_primary)), 0, headerString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return spannable;
  } else {
    return headerString;
  }
}
项目:GitHub    文件:PostViewModel.java   
public Spannable getPostAuthor() {
    String author = context.getString(R.string.text_post_author, post.by);
    SpannableString content = new SpannableString(author);
    int index = author.indexOf(post.by);
    if (!isUserPosts) content.setSpan(new UnderlineSpan(), index, post.by.length() + index, 0);
    return content;
}
项目:EmoticonGIFKeyboard    文件:EmoticonSearchAdapter.java   
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final Emoticon emoji = mData.get(position);
    if (emoji != null) {
        if (mEmoticonProvider != null
                && mEmoticonProvider.hasEmoticonIcon(emoji.getUnicode())) { //Check if the icon for this emoticon is available?

            //Convert to spannable.
            // Replace the emoticon image with provided by custom icon pack.
            Spannable spannable = new SpannableString(emoji.getUnicode());
            spannable.setSpan(new EmoticonSpan(mContext, mEmoticonProvider.getIcon(emoji.getUnicode()), mContext.getResources().getDimension(R.dimen.emoticon_grid_text_size)),
                    0,
                    spannable.length() - 1,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            holder.icon.setText(spannable);
        } else {
            holder.icon.setText(emoji.getUnicode());
        }
        holder.icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListener.OnEmoticonSelected(emoji);
            }
        });
    }
}
项目:CommentView    文件:SpanUtil.java   
public static Spannable getBoldSpan(String content) {
    if (TextUtils.isEmpty(content)) {
        return null;
    }
    SpannableString spannableString = new SpannableString(content);
    spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, content.length(), Constants.SPAN_FLAGS);
    return spannableString;
}
项目:GitHub    文件:RecyclerViewAdapterHelper.java   
/**
 * 处理关键字高亮
 * 如果需要检索算法库,请联系我
 *
 * @param originStr       被处理字符串
 * @param keyWord         关键字
 * @param hightLightColor 高亮颜色
 * @return CharSequence
 */
public static CharSequence handleKeyWordHighLight
(String originStr, String keyWord, @ColorInt int hightLightColor) {

    SpannableString ss = new SpannableString(originStr);
    Pattern p = Pattern.compile(keyWord);
    Matcher m = p.matcher(ss);

    while (m.find()) {
        ss.setSpan(new ForegroundColorSpan(hightLightColor), m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return ss;
}
项目:DailyStudy    文件:SpannableStringActivity.java   
/**
 * RelativeSizeSpan,设置文字相对大小,在TextView原有的文字大小的基础上,相对设置文字大小
 */
private void relativeSize () {
    SpannableString string = new SpannableString("设置文字的前景色为淡蓝色");
    RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.5f);
    string.setSpan(sizeSpan, 9, string.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
    bgtext.setText(string);
}
项目:letv    文件:StringUtils.java   
public static SpannableString highlightParamText(String inputString, int index, String highlight, int color) {
    inputString = String.format(inputString, new Object[]{highlight});
    SpannableString spanString = new SpannableString(inputString);
    if (!TextUtils.isEmpty(inputString)) {
        int beginPos = index;
        if (beginPos > -1) {
            spanString.setSpan(new ForegroundColorSpan(color), beginPos, highlight.length() + beginPos, 33);
        }
    }
    return spanString;
}
项目:GongXianSheng    文件:AbstractStockListFragment.java   
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    final StockItem bean = mStockList.get(position);
    StockItem.Product productBean = bean.getProduct();
    if (productBean != null) {
        if (!TextUtils.isEmpty(mKeyword)) {
            int index = productBean.getName().indexOf(mKeyword);
            if (index != -1) {
                SpannableString spannStr = new SpannableString(productBean.getName());
                spannStr.setSpan(new ForegroundColorSpan(Color.parseColor("#6bb400")), index, index + mKeyword.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                viewHolder.name.setText(spannStr);
            }
        } else {
            viewHolder.name.setText(productBean.getName());
        }
        viewHolder.number.setText(productBean.getDefaultCode() + " | ");
        viewHolder.content.setText(productBean.getUnit());
        if (productBean.getImage() !=null){
            FrecoFactory.getInstance(getActivity()).disPlay(viewHolder.sDv, RunwiseService.ENDPOINT + productBean.getImage().getImageSmall());
        }
    }
    viewHolder.value.setText(NumberUtil.getIOrD(String.valueOf(bean.getQty())));
    viewHolder.uom.setText(bean.getUom());
    if (TextUtils.isEmpty(bean.getLotNum())){
        viewHolder.dateNumber.setVisibility(View.INVISIBLE);
    }else{
        viewHolder.dateNumber.setText(bean.getLotNum());
        viewHolder.dateNumber.setVisibility(View.VISIBLE);
    }
    viewHolder.dateLate.setText(DateFormateUtil.getLaterFormat(bean.getLifeEndDate()));
}
项目:decoy    文件:AitHelper.java   
public static void replaceAitForeground(String value, SpannableString mSpannableString) {
    if (TextUtils.isEmpty(value) || TextUtils.isEmpty(mSpannableString)) {
        return;
    }
    Pattern pattern = Pattern.compile("(\\[有人@你\\])");
    Matcher matcher = pattern.matcher(value);
    while (matcher.find()) {
        int start = matcher.start();
        if (start != 0) {
            continue;
        }
        int end = matcher.end();
        mSpannableString.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
    }
}
项目:chromium-for-android-56-debug-video    文件:ItemChooserDialog.java   
/**
 * Shows an error message in the dialog.
 */
public void setErrorState(SpannableString errorMessage, SpannableString errorStatus) {
    mListView.setVisibility(View.GONE);
    mProgressBar.setVisibility(View.GONE);
    mEmptyMessage.setText(errorMessage);
    mEmptyMessage.setVisibility(View.VISIBLE);
    mStatus.setText(errorStatus);
}
项目:APIJSON-Android-RxJava    文件:PraiseTextView.java   
private void setSpan(SpannableString msp, final int index, int start, int end, final User user) {
    msp.setSpan(new ClickableSpan() {

        @Override
        public void onClick(View widget) {
            onNameClick(index, widget, user);
        }
    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);       
}