如何制作我的自定义ReplacementSpan包装?

时间:2015-03-30 15:31:57

标签: android spannablestring

我正在尝试将带边框的背景应用于TextView中的特定文字。 BackgroundColorSpan效果很好,但没有边框。要获得边框,我改为使用自定义ReplacementSpan并覆盖draw。对于简短的单词/句子看起来很好,但它无法包装线条。如何进行自定义ReplacementSpan换行?

enter image description here

enter image description here

enter image description here

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_replacement_span);

    final Context context = this;
    final TextView tv = (TextView) findViewById(R.id.tv);


    Spannable span = Spannable.Factory.getInstance().newSpannable("Some long string that wraps");
    //Works great, but no border:
    //span.setSpan(new BackgroundColorSpan(Color.GREEN), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

    //Has border, but doesn't wrap:
    span.setSpan(new BorderedSpan(context), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

    tv.setText(span, TextView.BufferType.SPANNABLE);
}


public static class BorderedSpan extends ReplacementSpan {
    final Paint mPaintBorder, mPaintBackground;
    int mWidth;
    Resources r;
    int mTextColor;

    public BorderedSpan(Context context) {
        mPaintBorder = new Paint();
        mPaintBorder.setStyle(Paint.Style.STROKE);
        mPaintBorder.setAntiAlias(true);

        mPaintBackground = new Paint();
        mPaintBackground.setStyle(Paint.Style.FILL);
        mPaintBackground.setAntiAlias(true);

        r = context.getResources();

        mPaintBorder.setColor(Color.RED);
        mPaintBackground.setColor(Color.GREEN);
        mTextColor = Color.BLACK;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        //return text with relative to the Paint
        mWidth = (int) paint.measureText(text, start, end);
        return mWidth;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        canvas.drawRect(x, top, x + mWidth, bottom, mPaintBackground);
        canvas.drawRect(x, top, x + mWidth, bottom, mPaintBorder);
        paint.setColor(mTextColor); //use the default text paint to preserve font size/style
        canvas.drawText(text, start, end, x, y, paint);
    }
}

0 个答案:

没有答案