首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spannable的Android paddings?

Spannable的Android paddings?
EN

Stack Overflow用户
提问于 2012-12-06 00:02:08
回答 1查看 2.1K关注 0票数 4

我使用下面的代码在TextView中设置文本的背景:

代码语言:javascript
复制
s.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.selection_blue)), prevIndex, index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

但是我也需要为这个文本设置填充。有可能吗?

EN

回答 1

Stack Overflow用户

发布于 2015-03-13 10:37:30

您可以使用ReplacementSpan。在您的活动中:

代码语言:javascript
复制
TextView tagsTextView = (TextView) mView.findViewById(R.id.tagsTextView);
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();

SpannableString tag = new SpannableString("TEST");
stringBuilder.append(tag);
stringBuilder.setSpan(new TagSpan(getResources().getColor(R.color.blue), getResources().getColor(R.color.white)), stringBuilder.length() - tag.length(), stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tagsTextView.setText(stringBuilder, TextView.BufferType.SPANNABLE);

TagSpan.java

代码语言:javascript
复制
public class TagSpan extends ReplacementSpan {
    private static final float PADDING = 50.0f;
    private RectF mRect;
    private int mBackgroundColor;
    private int mForegroundColor;

    public TagSpan(int backgroundColor, int foregroundColor) {
        this.mRect = new RectF();
        this.mBackgroundColor = backgroundColor;
        this.mForegroundColor = foregroundColor;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        // Background
        mRect.set(x, top, x + paint.measureText(text, start, end) + PADDING, bottom);
        paint.setColor(mBackgroundColor);
        canvas.drawRect(mRect, paint);

        // Text
        paint.setColor(mForegroundColor);
        int xPos = Math.round(x + (PADDING / 2));
        int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;
        canvas.drawText(text, start, end, xPos, yPos, paint);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
        return Math.round(paint.measureText(text, start, end) + PADDING);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13727343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档