欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

深入理解TextView实现Rich Text--在同一个TextView设置不同字体风格

程序员文章站 2023-12-06 10:29:10
背景介绍在开发应用过程中经常会遇到显示一些不同的字体风格的信息犹如默认的lockscreen上面的时间和充电信息。对于类似的情况,可能第一反应就是用不同的多个textvie...
背景介绍
在开发应用过程中经常会遇到显示一些不同的字体风格的信息犹如默认的lockscreen上面的时间和充电信息。对于类似的情况,可能第一反应就是用不同的多个textview来实现,对于每个textview设置不同的字体风格以满足需求。深入理解TextView实现Rich Text--在同一个TextView设置不同字体风格

这里推荐的做法是使用android.text.*;和android.text.style.*;下面的组件来实现richtext:也即在同一个textview中设置不同的字体风格。对于某些应用,比如文本编辑,记事本,彩信,短信等地方,还必须使用这些组件才能达到想到的显示效果。

主要的基本工具类有android.text.spanned; android.text.spannablestring; android.text.spannablestringbuilder;使用这些类来代替常规string。spannablestring和spannablestringbuilder可以用来设置不同的span,这些span便是用于实现rich text,比如粗体,斜体,前景色,背景色,字体大小,字体风格等等,android.text.style.*中定义了很多的span类型可供使用。

这是相关的api的class general hierarchy:深入理解TextView实现Rich Text--在同一个TextView设置不同字体风格

因为spannable等最终都实现了charsequence接口,所以可以直接把spannablestring和spannablestringbuilder通过textview.settext()设置给textview。
使用方法
当要显示rich text信息的时候,可以使用创建一个spannablestring或spannablestringbuilder,它们的区别在于spannablestring像一个string一样,构造对象的时候传入一个string,之后再无法更改string的内容,也无法拼接多个spannablestring;而spannablestringbuilder则更像是stringbuilder,它可以通过其append()方法来拼接多个string:

复制代码 代码如下:

spannablestring word = new spannablestring("the quick fox jumps over the lazy dog");
spannablestringbuilder multiword = new spannablestringbuilder();
multiword.append("the quick fox");
multiword.append("jumps over");
multiword.append("the lazy dog");

创建完spannable对象后,就可以为它们设置span来实现想要的rich text了,常见的span有:
•absolutesizespan(int size) ---- 设置字体大小,参数是绝对数值,相当于word中的字体大小
•relativesizespan(float proportion) ---- 设置字体大小,参数是相对于默认字体大小的倍数,比如默认字体大小是x, 那么设置后的字体大小就是x*proportion,这个用起来比较灵活,proportion>1就是放大(zoom in), proportion<1就是缩小(zoom out)
•scalexspan(float proportion) ---- 缩放字体,与上面的类似,默认为1,设置后就是原来的乘以proportion,大于1时放大(zoon in),小于时缩小(zoom out)
•backgroundcolorspan(int color) ----背景着色,参数是颜色数值,可以直接使用android.graphics.color里面定义的常量,或是用color.rgb(int, int, int)
•foregroundcolorspan(int color) ----前景着色,也就是字的着色,参数与背景着色一致
•typefacespan(string family) ----字体,参数是字体的名字比如“sans", "sans-serif"等
•stylespan(typeface style) -----字体风格,比如粗体,斜体,参数是android.graphics.typeface里面定义的常量,如typeface.bold,typeface.italic等等。
•strikethroughspan----如果设置了此风格,会有一条线从中间穿过所有的字,就像被划掉一样
对于这些sytle span在使用的时候通常只传上面所说明的构造参数即可,不需要设置其他的属性,如果需要的话,也可以对它们设置其他的属性,详情可以参见<>。
spannablestring和spannablestringbuilder都有一个设置上述span的方法:
复制代码 代码如下:

/**
 * set the style span to spannable, such as spannablestring or spannablestringbuilder
 * @param what --- the style span, such as stylespan
 * @param start --- the starting index of characters to which the style span to apply
 * @param end --- the ending index of characters to which the style span to apply
 * @param flags --- the flag specified to control
 */
setspan(object what, int start, int end, int flags);

其中参数what是要设置的style span,start和end则是标识string中span的起始位置,而 flags是用于控制行为的,通常设置为0或spanned中定义的常量,常用的有:
•spanned.span_exclusive_exclusive --- 不包含两端start和end所在的端点
•spanned.span_exclusive_inclusive --- 不包含端start,但包含end所在的端点
•spanned.span_inclusive_exclusive --- 包含两端start,但不包含end所在的端点
•spanned.span_inclusive_inclusive--- 包含两端start和end所在的端点
这里理解起来就好像数学中定义区间,开区间还是闭区间一样的。还有许多其他的flag,可以参考<这里>。这里要重点说明下关于参数0,有很多时候,如果设置了上述的参数,那么span会从start应用到text结尾,而不是在start和end二者之间,这个时候就需要使用flag 0。
linkify
另外,也可以对通过textview.setautolink(int)设置其linkify属性,其用处在于,textview会自动检查其内容,会识别出phone number, web address or email address,并标识为超链接,可点击,点击后便跳转到相应的应用,如dialer,browser或email。linkify有几个常用选项,更多的请参考<文档>
•linkify.email_address -- 仅识别出textview中的email在址,标识为超链接,点击后会跳到email,发送邮件给此地址
•linkify.phone_numbers -- 仅识别出textview中的电话号码,标识为超链接,点击后会跳到dialer,call这个号码
•linkify.web_urls-- 仅识别出textview中的网址,标识为超链接,点击后会跳到browser打开此url
•linkify.all -- 这个选项是识别出所有系统所支持的特殊uri,然后做相应的操作
权衡选择
个人认为软件开发中最常见的问题不是某个技巧怎么使用的问题,而是何时该使用何技巧的问题,因为实现同一个目标可能有n种不同的方法,就要权衡利弊,选择最合适的一个,正如常言所云,没有最好的,只有最适合的。如前面所讨论的,要想用不同的字体展现不同的信息可能的解法,除了用style span外还可以用多个textview。那么就需要总结下什么时候该使用stylespan,什么时候该使用多个textview:
1.如果显示的是多个不同类别的信息,就应该使用多个textview,这样也方便控制和改变各自的信息,例子就是默认lockscreen上面的日期和充电信息,因为它们所承载不同的信息,所以应该使用多个textview来分别呈现。
2.如果显示的是同一类信息,或者同一个信息,那么应该使用stylespan。比如,短信息中,要把联系人的相关信息突出显示;或是想要highlight某些信息等。
3.如果要实现rich text,没办法,只能使用style span。
4.如果要实现某些特效,也可以考虑使用stylespan。设置不同的字体风格只是style span的初级应用,如果深入研究,可以发现很多奇妙的功效。
实例
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">
  <scrollview
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
        <linearlayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
     <textview
       android:id="@+id/text_view_font_1"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       />
     <textview
       android:id="@+id/text_view_font_2"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       />
     <textview
       android:id="@+id/text_view_font_3"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       />
     <textview
       android:id="@+id/text_view_font_4"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       />
     <textview
       android:id="@+id/text_view_font_5"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       />
    </linearlayout>
    </scrollview>
</linearlayout>

source code:
复制代码 代码如下:

package com.android.effective;
import java.util.regex.matcher;
import java.util.regex.pattern;
import android.app.activity;
import android.graphics.color;
import android.graphics.typeface;
import android.os.bundle;
import android.text.spannable;
import android.text.spannablestring;
import android.text.spannablestringbuilder;
import android.text.style.absolutesizespan;
import android.text.style.backgroundcolorspan;
import android.text.style.foregroundcolorspan;
import android.text.style.quotespan;
import android.text.style.relativesizespan;
import android.text.style.scalexspan;
import android.text.style.strikethroughspan;
import android.text.style.stylespan;
import android.text.style.typefacespan;
import android.text.style.urlspan;
import android.text.util.linkify;
import android.widget.textview;
public class textviewfontactivity extends activity {
    @override
    public void oncreate(bundle bundle) {
        super.oncreate(bundle);
        setcontentview(r.layout.textview_font_1);

        // demonstration of basic spannablestring and spans usage
        final textview textwithstring = (textview) findviewbyid(r.id.text_view_font_1);
        string w = "the quick fox jumps over the lazy dog";
        int start = w.indexof('q');
        int end = w.indexof('k') + 1;
        spannable word = new spannablestring(w);
        word.setspan(new absolutesizespan(22), start, end,
                spannable.span_inclusive_inclusive);
        word.setspan(new stylespan(typeface.bold), start, end,
                spannable.span_inclusive_inclusive);
        word.setspan(new backgroundcolorspan(color.red), start, end,
                spannable.span_inclusive_inclusive);
        textwithstring.settext(word);

        // demonstration of basic spannablestringbuilder and spans usage
        final textview textwithbuilder = (textview) findviewbyid(r.id.text_view_font_2);
        spannablestringbuilder word2 = new spannablestringbuilder();
        final string one = "freedom is nothing but a chance to be better!";
        final string two = "the quick fox jumps over the lazy dog!";
        final string three = "the tree of liberty must be refreshed from time to time with " +
                "the blood of patroits and tyrants!";
        word2.append(one);
        start = 0;
        end = one.length();
        word2.setspan(new stylespan(typeface.bold_italic), start, end, spannable.span_exclusive_exclusive);
        word2.append(two);
        start = end;
        end += two.length();
        word2.setspan(new foregroundcolorspan(color.cyan), start, end,
                spannable.span_exclusive_exclusive);
        word2.append(three);
        start = end;
        end += three.length();
        word2.setspan(new urlspan(three), start, end, spannable.span_exclusive_exclusive);
        textwithbuilder.settext(word2);

        // troubleshooting when using spannablestringbuilder
        final textview texttroubles = (textview) findviewbyid(r.id.text_view_font_3);
        spannablestringbuilder word3 = new spannablestringbuilder();
        start = 0;
        end = one.length();
        // caution: must first append or set text to spannablestringbuilder or spannablestring
        // then set the spans to them, otherwise, indexoutofboundexception is thrown when setting spans
        word3.append(one);
        // for absolutesizespan, the flag must be set to 0, otherwise, it will apply this span to until end of text
        word3.setspan(new absolutesizespan(22), start, end, 0);//spannable.span_inclusive_inclusive);
        // for backgroundcolorspanspan, the flag must be set to 0, otherwise, it will apply this span to end of text
        word3.setspan(new backgroundcolorspan(color.dkgray), start, end, 0); //spannable.span_inclusive_inclusive);
        word3.append(two);
        start = end;
        end += two.length();
        word3.setspan(new typefacespan("sans-serif"), start, end,
                spannable.span_inclusive_inclusive);
        // todo: sometimes, flag must be set to 0, otherwise it will apply the span to until end of text
        // which might has nothing to do with specific span type.
        word3.setspan(new stylespan(typeface.bold_italic), start, end, 0);//spannable.span_inclusive_inclusive);
        word3.setspan(new scalexspan(0.618f), start, end, spannable.span_inclusive_inclusive);
        word3.setspan(new strikethroughspan(), start, end, 0);//spannable.span_inclusive_inclusive);
        word3.setspan(new foregroundcolorspan(color.cyan), start, end, spannable.span_inclusive_inclusive);
        word3.setspan(new quotespan(), start, end, 0); //spannable.span_inclusive_inclusive);
        word3.append(three);
        start = end;
        end += three.length();
        word3.setspan(new relativesizespan((float) math.e), start, end, spannable.span_inclusive_inclusive);
        word3.setspan(new foregroundcolorspan(color.blue), start, end, spannable.span_inclusive_inclusive);
        texttroubles.settext(word3);

        // highlight some patterns
        final string four = "the gap between the best software engineering " +
                "practice and the average practice is very wide¡ªperhaps wider " +
                " than in any other engineering discipline. a tool that disseminates " +
                "good practice would be important.¡ªfred *s";
        final pattern highlight = pattern.compile("the");
        final textview texthighlight = (textview) findviewbyid(r.id.text_view_font_4);
        spannablestring word4 = new spannablestring(four);
        matcher m = highlight.matcher(word4.tostring());
        while (m.find()) {
            word4.setspan(new stylespan(typeface.bold_italic), m.start(), m.end(),
                    spannable.span_inclusive_inclusive);
            word4.setspan(new foregroundcolorspan(color.red), m.start(), m.end(),
                    spannable.span_inclusive_inclusive);
            word4.setspan(new strikethroughspan(), m.start(), m.end(),
                    spannable.span_inclusive_inclusive);
        }
        texthighlight.settext(word4);

        // set numbers, urls and e-mail address to be clickable with textview#setautolinkmask
        final textview textclickable = (textview) findviewbyid(r.id.text_view_font_5); 
        final string contact = "email: mvp@microsoft.com\n" +
                "phone: +47-24885883\n" +
                "fax: +47-24885883\n" +
                "http: www.microsoft.com/mvp.asp";
        // set the attribute first, then set the text. otherwise, it won't work
        textclickable.setautolinkmask(linkify.all); // or set 'android:autolink' in layout xml
        textclickable.settext(contact);
    }
}

the results:

深入理解TextView实现Rich Text--在同一个TextView设置不同字体风格深入理解TextView实现Rich Text--在同一个TextView设置不同字体风格