ITPub博客

首页 > IT职业 > IT生活 > Android开发笔记——TextView文本设置不同颜色

Android开发笔记——TextView文本设置不同颜色

IT生活 作者:markriver 时间:2021-09-09 09:41:48 0 删除 编辑
1.只贴代码,不解释,留作以后用/**
 * @param tv             Display a message that include title and content
 * @param title          Title of message
 * @param content        Content of message
 * @param titleColorID   The color id for Title
 * @param contentColorID The color id for Content
 */
public static void colorForTextView(Context context, TextView tv, String title, String content, 
					int titleColorID, int contentColorID) {
    if (content == null) {
        content = "";
    }
    SpannableStringBuilder spannableBuilder = new SpannableStringBuilder();
    ForegroundColorSpan titleColorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, titleColorID));
    ForegroundColorSpan contentColorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, contentColorID));

    spannableBuilder.append(title);
    int temp = spannableBuilder.length();
    spannableBuilder.setSpan(titleColorSpan, 0, temp, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    spannableBuilder.append(content);
    spannableBuilder.setSpan(contentColorSpan, temp, spannableBuilder.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
    tv.setText(spannableBuilder, TextView.BufferType.SPANNABLE);
}

原文链接:http://www.apkbus.com/blog-184446-78220.html

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/818/viewspace-2806181/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2020-07-03

  • 博文量
    502
  • 访问量
    18492