TextView部分文字加粗

开发中经常遇到TextView中部分文字加粗或者颜色不同的场景
一般使用SpannableString就能解决。例如:

    private void testText1(String posName) {
        String text = "* 为你发布的 " + posName + " 添加一句宣传语吧!";
        SpannableString span = new SpannableString(text);
        span.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.CYAN), 7, 7 + posName.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.BLACK), text.length() - 5, text.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new StyleSpan(Typeface.BOLD), text.length() - 5, text.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv1.setText(span);
        /**
         * 其中最后的参数flag:
         * Spanned.SPAN_EXCLUSIVE_EXCLUSIVE --- 不包含两端start和end所在的端点 (a,b)
         * Spanned.SPAN_EXCLUSIVE_INCLUSIVE --- 不包含端start,但包含end所在的端点 (a,b]
         * Spanned.SPAN_INCLUSIVE_EXCLUSIVE --- 包含两端start,但不包含end所在的端点 [a,b)
         * Spanned.SPAN_INCLUSIVE_INCLUSIVE --- 包含两端start和end所在的端点 [a,b]
         */
    }

效果图如下:
TextView部分文字加粗_第1张图片
虽然这种方式能设置很多特效,但是setSpan的需要传入起始值的下标,字符串往往是后台给出一部分,app端写死一部分,哪个位置加粗变色都需要我们手动数出下标,真是让人掉头发。所以我更喜欢使用html,例如这样:

    private void testText2(String posName) {
        String text = "* 为你发布的"
                + " " + posName + " "
                + "添加一句宣传语吧!";
        tv2.setText(Html.fromHtml(text));
    }

效果是这样的:

TextView部分文字加粗_第2张图片
但是使用html加粗文字时需要格外注意:需要使用需要加粗文字,其他没效果的

    private void testText2(String posName) {
        String text = "* 为你发布的"
                + " " + posName + " "
                + "添加一句"
                + "宣传语" 
                + "吧!";
        tv2.setText(Html.fromHtml(text));
    }

但是使用TextView.setText(Html.fromhtml(text);有个bug,假如text包含1+1<3等包含类似html标签的小于号,且没有大于号配对时,会出现文字不全情况。
TextView部分文字加粗_第3张图片
TextView部分文字加粗_第4张图片
并没有找到合适的解决方案:

只是发现了一些可能有用的帖子:

Strange issue with android:ellipsize=“end”

android ellipsize multiline textview

你可能感兴趣的:(TextView加粗,Android)