如果我在textview android

时间:2017-04-12 10:48:00

标签: android spannablestring

下面的代码在spannableString

中设置了虚线下划线
private static class DottedUnderlineSpan extends ReplacementSpan {
    private Paint p;
    private int mWidth;
    private String mSpan;

    private float mSpanLength;
    private boolean mLengthIsCached = false;

    private float mOffsetY;

    public DottedUnderlineSpan(int _color, String _spannedText, float dashPathEffect,
                               float strokeWidth, float offsetY) {
        p = new Paint();
        p.setColor(_color);
        p.setStyle(Paint.Style.STROKE);
        p.setPathEffect(new DashPathEffect(new float[]{dashPathEffect, dashPathEffect}, 0));
        p.setStrokeWidth(strokeWidth);
        mSpan = _spannedText;
        mOffsetY = offsetY;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end,
                       Paint.FontMetricsInt fm) {
        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.drawText(text, start, end, x, y, paint);
        if (!mLengthIsCached)
            mSpanLength = paint.measureText(mSpan);

        // https://code.google.com/p/android/issues/detail?id=29944
        // canvas.drawLine can't draw dashes when hardware acceleration is enabled,
        // but canvas.drawPath can
        Path path = new Path();
        path.moveTo(x, y + mOffsetY);
        path.lineTo(x + mSpanLength, y + mOffsetY);
        canvas.drawPath(path, this.p);
    }
}

这里我打电话给上面的课程并设置虚线下划线。

SpannableString spannableText = new SpannableString("Hello, How are you");
spannableText.setSpan(new DottedUnderlineSpan(fromColor("#b5d189"), "How", dashPathEffect,strokeWidth, offsetY),7,9,0);
spannableText.setSpan(new ForegroundColorSpan(fromColor("#7ac902")),7, 9,0);
textView.setText(spannableText);
textView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
textView.setMovementMethod(LinkMovementMethod.getInstance());

这里我的问题是ForegroundColorSpan无法正常工作我不知道为什么? 如果我删除

spannableText.setSpan(new DottedUnderlineSpan(fromColor("#b5d189"), "How", dashPathEffect,strokeWidth, offsetY),7,9,0);

代码然后ForegroundColorspan完美运作。

我希望How字为绿色,带虚线下划线。 有人可以帮助我吗?

0 个答案:

没有答案