Java Code Examples for android.text.SpannableString

The following are top voted examples for showing how to use android.text.SpannableString. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Quizca-UI-Concept   File: MainActivity.java   View source code 7 votes vote down vote up
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;
}
 
Example 2
Project: ChenYan   File: Main2Activity.java   View source code 7 votes vote down vote up
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);

    }
 
Example 3
Project: IslamicLibraryAndroid   File: SearchResult.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: Nird2   File: UiUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 5
Project: AgentWeb   File: AgentWebUtils.java   View source code 6 votes vote down vote up
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();

}
 
Example 6
Project: GitHub   File: BookMarkAdapter.java   View source code 6 votes vote down vote up
@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", ""));
    }

}
 
Example 7
Project: PocketGopher   File: UnknownPage.java   View source code 6 votes vote down vote up
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);
        }
    });
}
 
Example 8
Project: revolution-irc   File: UserAutoRunCommandHelper.java   View source code 6 votes vote down vote up
@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();
}
 
Example 9
Project: Tusky   File: MentionTokenizer.java   View source code 6 votes vote down vote up
@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 + " ";
    }
}
 
Example 10
Project: AndroidUtilCode-master   File: SnackbarUtils.java   View source code 6 votes vote down vote up
/**
 * 设置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();
}
 
Example 11
Project: SimpleDialogFragments   File: MainActivity.java   View source code 6 votes vote down vote up
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));
    }
}
 
Example 12
Project: ultrasonic   File: SelectPlaylistActivity.java   View source code 6 votes vote down vote up
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();
}
 
Example 13
Project: TextReader   File: BookContentTextView.java   View source code 6 votes vote down vote up
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());
    }
}
 
Example 14
Project: PeSanKita-android   File: ComposeText.java   View source code 6 votes vote down vote up
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));
  }
}
 
Example 15
Project: orgzly-android   File: TitleGenerator.java   View source code 6 votes vote down vote up
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;
}
 
Example 16
Project: yyox   File: OrderDetailActivity.java   View source code 6 votes vote down vote up
@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();
        }
    }
 
Example 17
Project: MultiContactPicker   File: MultiContactPickerAdapter.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 18
Project: orgzly-android   File: SpaceTokenizer.java   View source code 6 votes vote down vote up
@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 + " ";
        }
    }
}
 
Example 19
Project: QueryHighlighter   File: QueryHighlighter.java   View source code 5 votes vote down vote up
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;
    }
}
 
Example 20
Project: RetrofitSample   File: DlEmptyLayout.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 21
Project: GongXianSheng   File: DateFormateUtil.java   View source code 5 votes vote down vote up
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;
	}
}
 
Example 22
Project: Aurora   File: UiUtils.java   View source code 5 votes vote down vote up
/**
 * 设置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)); // 一定要进行转换,否则属性会消失
}
 
Example 23
Project: yjPlay   File: GestureVideoPlayer.java   View source code 5 votes vote down vote up
/****
 * 滑动进度
 *
 * @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);
    }
}
 
Example 24
Project: q-mail   File: ICalendarHelper.java   View source code 5 votes vote down vote up
@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();
}
 
Example 25
Project: q-mail   File: ICalendarHelper.java   View source code 5 votes vote down vote up
@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();
}
 
Example 26
Project: q-mail   File: MessageHelper.java   View source code 5 votes vote down vote up
@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();
}
 
Example 27
Project: NeiHanDuanZiTV   File: ArmsUtils.java   View source code 5 votes vote down vote up
/**
 * 设置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)); // 一定要进行转换,否则属性会消失
}
 
Example 28
Project: GitHub   File: PiePolylineChartActivity.java   View source code 5 votes vote down vote up
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;
    }
 
Example 29
Project: FastLib   File: SnackBarUtil.java   View source code 5 votes vote down vote up
/**
 * 显示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();
}
 
Example 30
Project: Cable-Android   File: ContactSelectionListAdapter.java   View source code 5 votes vote down vote up
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;
  }
}
 
Example 31
Project: GitHub   File: PostViewModel.java   View source code 5 votes vote down vote up
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;
}
 
Example 32
Project: EmoticonGIFKeyboard   File: EmoticonSearchAdapter.java   View source code 5 votes vote down vote up
@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);
            }
        });
    }
}
 
Example 33
Project: CommentView   File: SpanUtil.java   View source code 5 votes vote down vote up
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;
}
 
Example 34
Project: GitHub   File: RecyclerViewAdapterHelper.java   View source code 5 votes vote down vote up
/**
 * 处理关键字高亮
 * 如果需要检索算法库,请联系我
 *
 * @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;
}
 
Example 35
Project: DailyStudy   File: SpannableStringActivity.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 36
Project: letv   File: StringUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 37
Project: GongXianSheng   File: AbstractStockListFragment.java   View source code 5 votes vote down vote up
@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()));
}
 
Example 38
Project: decoy   File: AitHelper.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 39
Project: chromium-for-android-56-debug-video   File: ItemChooserDialog.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 40
Project: APIJSON-Android-RxJava   File: PraiseTextView.java   View source code 5 votes vote down vote up
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);		
}