Android开发之SpannableStringBuilder手记

SpannableStringBuilder

SpannableStringBuilderd的功能

扩展TextView中的内容,包括在TextView中添加图片,控制部分文字的大小,颜色和背景色,以及可以设置TextView任意内容的点击事件等
SpannableStringBuilderd功能演示
SpannableStringBuilderd功能演示
示例代码如下:

        strText=findViewById(R.id.strText);
        SpannableStringBuilder ssb=new SpannableStringBuilder("你好 ,安卓!");
        //设置字体颜色
        ForegroundColorSpan fcs=new ForegroundColorSpan(ContextCompat.getColor(this,R.color.colorPrimary));
        ssb.setSpan(fcs,0,4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        //设置背景颜色
        BackgroundColorSpan bcs=new BackgroundColorSpan(ContextCompat.getColor(this,R.color.colorAccent));
        ssb.setSpan(bcs,0,4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        AbsoluteSizeSpan ass=new AbsoluteSizeSpan(80);
        //设置字体大小
        ssb.setSpan(ass,0,4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        StyleSpan ss=new StyleSpan(Typeface.BOLD);
        //设置字体类型
        ssb.setSpan(ss,0,4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        ImageSpan is=new ImageSpan(this,R.mipmap.ic_launcher);
        //添加图片
        ssb.setSpan(is,4,6,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        //点击事件
        ClickableSpan cs=new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Toaster.showShort(MainActivity.this,"你好,Grooter!");
            }
        };
        ssb.setSpan(cs,4,6,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        strText.setText(ssb);
        //为TextView添加链接
        strText.setMovementMethod(LinkMovementMethod.getInstance());

该类实现Spannable
Spannable继承Spanned

猜你喜欢

转载自blog.csdn.net/figurers/article/details/79778140