Android SpannableString 在部分文本后面设置背景 [英] Android SpannableString set background behind part of text

查看:19
本文介绍了Android SpannableString 在部分文本后面设置背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建与此图片类似的东西:

I would like to create something similar as seen on this image:

我设法用 SpannableStringBuilder 创建了evertyhing,橙色圆角矩形除外.我可以使用 BackgroundColorSpan 将背景设置为该颜色,但我找不到使它变圆的方法.有什么想法可以实现吗?

I managed to create evertyhing with SpannableStringBuilder, except the orange rounded rectangle. I can set the background to that color with BackgroundColorSpan, but I can't find a way to make it rounded. Any ideas how can I achieve this?

提前致谢!

我正在使用 Xamarin.Android,但这是我的代码:

I'm using Xamarin.Android, but here is my code:

stringBuilder.SetSpan(new BackgroundColorSpan(Application.Context.Resources.GetColor(Resource.Color.orangeColor)), stringBuilder.Length() - length, stringBuilder.Length(), SpanTypes.ExclusiveExclusive);

推荐答案

根据 pskink 的建议,我设法解决了我的问题.这是我的课:

I managed to solve my problem, based on pskink's suggestion. Here is my class:

public class RoundedBackgroundSpan : ReplacementSpan
{
    public override void Draw(Canvas canvas, ICharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint)
    {
        var rect = new RectF(x, top, x + MeasureText(paint, text, start, end), bottom);
        paint.Color = Application.Context.Resources.GetColor(Resource.Color.nextTimeBackgroundColor);
        canvas.DrawRoundRect(rect, Application.Context.Resources.GetDimensionPixelSize(Resource.Dimension.localRouteDetailsRoundRectValue), Application.Context.Resources.GetDimensionPixelSize(Resource.Dimension.localRouteDetailsRoundRectValue), paint);
        paint.Color = Application.Context.Resources.GetColor(Resource.Color.nextTimeTextColor);
        canvas.DrawText(text, start, end, x, y, paint);
    }

    public override int GetSize(Paint paint, ICharSequence text, int start, int end, Paint.FontMetricsInt fm)
    {
        return Math.Round(MeasureText(paint, text, start, end));
    }

    private float MeasureText(Paint paint, ICharSequence text, int start, int end)
    {
        return paint.MeasureText(text, start, end);
    }
}

示例用法:

var stringBuilder = new SpannableStringBuilder();
var stringToAppend = "hello world";
stringBuilder.Append(stringToAppend);
stringBuilder.SetSpan(new RoundedBackgroundSpan(), stringBuilder.Length() - stringToAppend.Length, stringBuilder.Length(), SpanTypes.ExclusiveExclusive);

这篇关于Android SpannableString 在部分文本后面设置背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆