Android 富文本SpannableString

一、认识SpannableString

  • 为什么要使用富文本
    在Android开发中,有很多UI会画出一些特别炫酷的界面出来,比如一个字符串里有特殊的字会有其他颜色并加粗、变大变小、插入小图片、给某几个文字添加边框,如果我们使用笨办法用几个TextView或者ImageView来链接,这样虽然能实现但是会不会很笨重,如果出现换行就尴尬了,他不能想做到无缝换行造成效果跟预期效果相差太大,如果效果很复杂是不是会给应用增加体验负担?还会给带来适配的问题,SpannableString的出现帮我们解决了这一系列的问题。

  • 他能给我们带来什么
    解决复杂的字符串效果UI效果,

二、 如何实现SpannableString的功能效果

  • 比较常用的Span样式
  1. BackgroundColorSpan : 文本背景色、
  2. ForegroundColorSpan : 文本颜色
  3. MaskFilterSpan : 修饰效果,如模糊(BlurMaskFilter)浮雕
  4. RasterizerSpan : 光栅效果
  5. StrikethroughSpan : 删除线
  6. SuggestionSpan : 相当于占位符
  7. UnderlineSpan : 下划线
  8. AbsoluteSizeSpan : 文本字体(绝对大小)
  9. DynamicDrawableSpan : 设置图片,基于文本基线或底部对齐。
  10. ImageSpan : 图片
  11. RelativeSizeSpan : 相对大小(文本字体)
  12. ScaleXSpan : 基于x轴缩放
  13. StyleSpan : 字体样式:粗体、斜体等
  14. SubscriptSpan : 下标(数学公式会用到)
  15. SuperscriptSpan : 上标(数学公式会用到)
  16. TextAppearanceSpan : 文本外貌(包括字体、大小、样式和颜色)
  17. TypefaceSpan : 文本字体
  18. URLSpan : 文本超链接
  19. ClickableSpan : 点击事件

效果:

在这里插入图片描述

public class CommShowSpanActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comm_show_span);
        TextView text = findViewById(R.id.text);
        text.setTextSize(23);

        String str = "东风路看对方了困难发了多少你疯啦百度一下上岛咖啡了上来看待离开克里斯丁肺宁颗粒道德积分呢小四的减肥我欧艾斯都放开克里斯丁肺宁颗粒道德积分呢小四的减肥我欧艾斯都放开克里斯丁肺宁颗粒道德积分呢小四的减肥我欧艾斯都放假哦吉安市都放假哦so";
        SpannableString spannableString = new SpannableString(str);


        /*字体变大变小*/
        AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(80);
        spannableString.setSpan(sizeSpan, 0, 3, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        /*某个字符串改变颜色*/
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);
        spannableString.setSpan(foregroundColorSpan, 3, 6, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        /*字符串的背景色*/
        BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.YELLOW);
        spannableString.setSpan(backgroundColorSpan, 6, 8, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        /*下划线  颜色随字体颜色 */
        UnderlineSpan underlineSpan = new UnderlineSpan();
        spannableString.setSpan(underlineSpan, 0, 8, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        /*删除线*/
        StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
        spannableString.setSpan(strikethroughSpan, 8, 12, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        /*暂位符*/
        SuggestionSpan suggestionSpan = new SuggestionSpan(CommShowSpanActivity.this, new String[]{
                "0000", "1111"
        }, SuggestionSpan.FLAG_EASY_CORRECT);
        spannableString.setSpan(suggestionSpan, 8, 12, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        //Typeface  加粗
        StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
        spannableString.setSpan(styleSpan, 12, 16, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        /*斜体文本*/
        StyleSpan styleSpan1 = new StyleSpan(Typeface.ITALIC);
        spannableString.setSpan(styleSpan1, 12, 16, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        /*超链接*/
        URLSpan urlSpan = new URLSpan("http://www.baidu.com");
        spannableString.setSpan(urlSpan, 16, 20, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        /*文本字体*/
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
            TypefaceSpan typefaceSpan = new TypefaceSpan("");
            spannableString.setSpan(typefaceSpan, 16, 20, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }


        /*修饰效果,如模糊(BlurMaskFilter)*/
        MaskFilterSpan maskFilterSpan = new MaskFilterSpan(new BlurMaskFilter(12, BlurMaskFilter.Blur.SOLID));
        spannableString.setSpan(maskFilterSpan, 20, 25, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        //浮雕
        MaskFilterSpan maskFilterSpan1 = new MaskFilterSpan(new EmbossMaskFilter(new float[]{
                10, 20, 30
        }, 0.5f, 0.5f, 15));
        spannableString.setSpan(maskFilterSpan1, 25, 30, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);



        //TextAppearanceSpan 文本外貌(包括字体、大小、样式和颜色)
        TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan(this, R.style.text);
        spannableString.setSpan(textAppearanceSpan, 30, 33, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        TextAppearanceSpan textAppearanceSpan1 = new TextAppearanceSpan(this,
                android.R.style.TextAppearance_Theme,getResources().getColor(R.color.colorPrimary));
        spannableString.setSpan(textAppearanceSpan1, 34, 35, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        /**
         * DynamicDrawableSpan 设置图片,基于文本基线或底部对齐。
         */
        DynamicDrawableSpan drawableSpan =
                new DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BASELINE) {
                    @Override
                    public Drawable getDrawable() {
                        Drawable d = getResources().getDrawable(R.mipmap.add_pic);
                        d.setBounds(0, 0, d.getIntrinsicWidth()/2, d.getIntrinsicHeight()/2);
                        return d;
                    }
                };
        spannableString.setSpan(drawableSpan, 3, 4, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);




        DynamicDrawableSpan drawableSpan2 = new DynamicDrawableSpan(
                DynamicDrawableSpan.ALIGN_BOTTOM) {
            @Override
            public Drawable getDrawable() {
                Drawable d = getResources().getDrawable(R.mipmap.add_pic);
                d.setBounds(0, 0, 50, 50);
                return d;
            }
        };
        spannableString.setSpan(drawableSpan2, 7, 8, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        /**
         * 设置字体相对大小
         */
        RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(2);
        spannableString.setSpan(relativeSizeSpan, 50, 60, Spannable.SPAN_INCLUSIVE_INCLUSIVE);


        /**
         * 下标脚注
         */
        SubscriptSpan subscriptSpan = new SubscriptSpan();
        spannableString.setSpan(subscriptSpan, 69, 70, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.RED),69, 70, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        /**
         * 上标
         */
        SuperscriptSpan superscriptSpan = new SuperscriptSpan();
        spannableString.setSpan(superscriptSpan, 76, 77, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.RED),76, 77, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        text.setText(spannableString);
        text.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

  • ReplacementSpan给一串字符串中的某两个文字添加背景或者边框

效果:
在这里插入图片描述

代码:

public class TagBgSpan extends ReplacementSpan {

    /**
     * 当前tag的宽度
     */
    public int currentMeasureTextWidth;
    /**
     * 左右間距
     */
    public int paddingLandR = 10;
    /**
     * 标签之前的间距
     */
    public int speed = 10;
    /**
     * 圆角
     */
    private int radius = 10;

    /**
     * 背景色
     */
    private int bgColor = Color.GRAY;

    /**
     * 画笔的风格
     */
    private Paint.Style style = Paint.Style.STROKE;

    /**
     * 標簽颜色
     */
    private int tagTextColor = Color.RED;


    public TagBgSpan setTagTextColor(int tagTextColor) {
        this.tagTextColor = tagTextColor;
        return this ;
    }

    public TagBgSpan setStyle(Paint.Style style) {
        this.style = style;
        return this ;
    }


    public TagBgSpan setBgColor(int bgColor) {
        this.bgColor = bgColor;
        return this;
    }


    public TagBgSpan setSpeed(int speed) {
        this.speed = speed;
        return this;
    }

    public TagBgSpan setRadius(int radius) {
        this.radius = radius;
        return this ;
    }


    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        currentMeasureTextWidth = (int) (paint.measureText(text.toString(), start, end) + (paddingLandR * 2) + (speed * 2));
        return currentMeasureTextWidth;
    }


    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        paint.setColor(bgColor);
        paint.setStyle(style);
        RectF rect = new RectF(x + speed, top, x + currentMeasureTextWidth - speed, bottom);
        canvas.drawRoundRect(rect, radius, radius, paint);


        paint.setColor(tagTextColor);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        canvas.drawText(text, start, end, x + speed + paddingLandR, y, paint);
    }
}

  • ClickableSpan实现一串字符串中某几个文字支持点击功能
    效果:
    效果

代码:

public class MyClickableSpan extends ClickableSpan {

    private Context context ;

    public MyClickableSpan(Context context ){
        this.context=context;
    }

    @Override
    public void updateDrawState(@NonNull TextPaint ds) {
        super.updateDrawState(ds);
        ds.setColor(Color.RED);
        ds.setFakeBoldText(true);
    }

    @Override
    public void onClick(@NonNull View widget) {
        Toast.makeText(context,"测试onClick",Toast.LENGTH_SHORT).show();
    }
}

  • ImageSpan实现在字符串中插入图片

效果:
在这里插入图片描述

代码:

public class MyImageSpan extends ImageSpan {


    public MyImageSpan(@NonNull Context context, @NonNull Bitmap bitmap) {
        super(context, bitmap);
    }


    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        return getDrawable().getIntrinsicWidth();
    }


    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        super.draw(canvas, text, start, end, x, top, y, bottom, paint);
        Drawable b = getDrawable();
        Paint.FontMetricsInt fm = paint.getFontMetricsInt();
        int transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;
        canvas.save();
        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Android 富文本编辑是指在Android平台上的文本编辑中,可以实现富文本样式的编辑和展示。富文本通常包括文字样式(如字体、大小、颜色)、文本格式(如加粗、斜体、下划线)和图片等不同类型的内容。 Android提供了一些工具和库来实现富文本编辑,最常用的就是使用SpannableString类。SpannableString类是Android提供的一个可变的字符序列,它可以应用于文字的样式和格式。我们可以通过使用SpannableString的相关方法来给特定的文字设置样式,比如设置字体颜色、设置下划线等。 此外,Android还提供了一些内置的Span类,如ForegroundColorSpan用于设置文字颜色、BackgroundColorSpan用于设置文字背景颜色、StyleSpan用于设置文字样式等等。我们可以通过将这些Span类与SpannableString一起使用,来实现富文本编辑的效果。 值得一提的是,除了文字样式之外,富文本编辑还可以包括图片和链接的插入。Android提供了ImageSpan类和ClickableSpan类用于实现这些功能。通过使用ImageSpan,我们可以将图片插入到富文本中,而使用ClickableSpan,我们可以将文字设置为可点击的链接,实现跳转功能。 总的来说,Android提供了丰富的工具和类用于富文本编辑,开发者可以根据自己的需求选择合适的方案来实现富文本编辑功能。无论是文字的样式、格式,还是图片和链接的插入,Android都提供了相应的类和方法来满足开发者的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

将哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值