Android TextView 实现文字大小不同和文字颜色不同

效果图例如以下:


关键代码例如以下:

StringBuffer sb = new StringBuffer();
                if(day > 0) {
                    sb.append("<a href=\"1\">");
                    sb.append(""+day);
                    sb.append("</a>");
                    sb.append(""+Global.getString(R.string.unit_Day2));
                }

                sb.append("<a href=\"2\">");
                if(hour > 9) {
                    sb.append(" "+hour);
                } else {
                    sb.append(" 0"+hour);
                }
                sb.append("</a>");
                sb.append(""+Global.getString(R.string.unit_Hour2));

                sb.append("<a href=\"3\">");
                if(minute > 9) {
                    sb.append(" "+minute);
                } else {
                    sb.append(" 0"+minute);
                }
                sb.append("</a>");
                sb.append(""+Global.getString(R.string.unit_Minute2));

                sb.append("<a href=\"4\">");
                if(second > 9) {
                    sb.append(" " + second);
                } else {
                    sb.append(" 0" + second);
                }
                sb.append("</a>");
                sb.append(""+Global.getString(R.string.unit_Second));

                int end = sb.length();
                SpannableString ss = new SpannableString(Html.fromHtml(sb.toString()));
                URLSpan[] urls = ss.getSpans(0, end, URLSpan.class);

                String resultStr = sb.toString();
                Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE);
                Matcher m_html = p_html.matcher(resultStr);
                resultStr = m_html.replaceAll(""); // 过滤html标签
                SpannableString span = new SpannableString(resultStr);
                for (URLSpan url : urls) {
                    int startIndex = ss.getSpanStart(url);
                    int endIndex = ss.getSpanEnd(url);
                    // 原字两倍大小
                    span.setSpan(new AbsoluteSizeSpan(Global.dpToPx(24)), startIndex, endIndex,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    // 设置样式2
                    span.setSpan(new ForegroundColorSpan(Color.WHITE),
                            startIndex, endIndex,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    // 设置样式3
                    span.setSpan(new StyleSpan(Typeface.BOLD),
                            startIndex, endIndex,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                }

                mBottomLL2_Detail.setText(span);

说明:

1.主要原理为使用SpannableString来做多样式的String给TextView显示

2.用到<a href>标签的原因是为了做到国际化,由于span是依照index来多样化的,所以须要用href来标识多样化的index

posted @ 2016-04-17 18:44  phlsheji  阅读(875)  评论(0编辑  收藏  举报