TextView与背景颜色和行间距

时间:2014-04-08 14:19:31

标签: android background textview html

我希望显示如下文字......

enter image description here

我的编码如下:

SpannableString sText = new SpannableString(text);
sText.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

holder.txtText.setLineSpacing(0, 1.5f);
textView.setText(sText);

7 个答案:

答案 0 :(得分:5)

试试这个。 创建自定义TextView并覆盖方法绘制(Canvas画布)。

public class BgColorTextView extends TextView {
    public BgColorTextView(Context context) {
        super(context);
    }

    public BgColorTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BgColorTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public BgColorTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void draw(Canvas canvas) {
        int lineCount = getLayout().getLineCount();
        Rect rect = new Rect();
        Paint paint = new Paint();
        paint.setColor(getResources().getColor(R.color.YOUR_CUSTOM_COLOR));
        for (int i = 0; i < lineCount; i++) {
            rect.top = (getLayout().getLineTop(i));
            rect.left = (int) getLayout().getLineLeft(i);
            rect.right = (int) getLayout().getLineRight(i);
            rect.bottom = (int) (getLayout().getLineBottom(i) - ((i + 1 == lineCount) ? 0 : getLayout().getSpacingAdd()));

            canvas.drawRect(rect, paint);
        }
        super.draw(canvas);
    }
}

答案 1 :(得分:2)

已经很长时间了,但我会把静态方法放在下面。希望它会帮助另一个人。

public static void setTextWithSpan(final TextView textView, int backgroundColor, String text, float lineSpacingMultiplier) {
    class BackgroundColorSpanWithPaddingAndLineSpacing implements LineBackgroundSpan {
        private float roundedCornerSize;
        private int backgroundColor;
        private int paddingSize;
        private RectF rect;

        private BackgroundColorSpanWithPaddingAndLineSpacing(int backgroundColor, int paddingSize, float roundedCornerSize) {
            super();
            this.backgroundColor = backgroundColor;
            this.paddingSize = paddingSize;
            this.roundedCornerSize = roundedCornerSize;
            this.rect = new RectF();
        }

        @Override
        public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int currentLineNumber) {
            final int textWidth = Math.round(p.measureText(text, start, end));
            final int paintColor = p.getColor();

            rect.set(left - paddingSize / 2, top - paddingSize / 4, left + textWidth + paddingSize / 2, top + textView.getTextSize() + paddingSize / 2);
            p.setColor(backgroundColor);
            c.drawRoundRect(rect, roundedCornerSize, roundedCornerSize, p);
            p.setColor(paintColor);
        }
    }

    int padding = textView.getPaddingLeft();
    int radius = padding / 2;

    SpannableStringBuilder builder = new SpannableStringBuilder(text);
    BackgroundColorSpanWithPaddingAndLineSpacing backgroundSpan = new BackgroundColorSpanWithPaddingAndLineSpacing(backgroundColor, padding, radius);
    builder.setSpan(backgroundSpan, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    textView.setShadowLayer(padding, 0, 0, 0);
    textView.setLineSpacing(0, lineSpacingMultiplier);

    textView.setText(builder, TextView.BufferType.SPANNABLE);
}

用法:

SpanUtils.setTextWithSpan(titleTv, android.graphics.Color.BLUE, textStr, 1.4f);

我确定您可以根据自己的需要进行修改。

答案 2 :(得分:0)

基于this的经过修改的解决方案,可以选择设置颜色,并且使用Kotlin:

//https://stackoverflow.com/a/30096905/878126
class BgColorTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr) {
    @Suppress("MemberVisibilityCanBePrivate")
    var backgroundTextColor = -0x145bfb
        set(value) {
            field = value
            invalidate()
        }

    override fun draw(canvas: Canvas) {
        val currentLayout = layout
        if (currentLayout == null) {
            super.draw(canvas)
            return
        }
        val lineCount = currentLayout.lineCount
        val rect = Rect()
        val paint = Paint()
        paint.color = backgroundTextColor
        for (i in 0 until lineCount) {
            rect.top = currentLayout.getLineTop(i)
            rect.left = currentLayout.getLineLeft(i).toInt()
            rect.right = currentLayout.getLineRight(i).toInt()
            rect.bottom = currentLayout.getLineBottom(i) - (if (i + 1 == lineCount) 0 else currentLayout.spacingAdd.toInt())
            canvas.drawRect(rect, paint)
        }
        super.draw(canvas)
    }
}

答案 3 :(得分:0)

对于那些有相同问题的人,您可以创建一个新类Extending ReplacemntSpan类并重写它的draw方法,如下所示:


public class RoundedBackgroundSpan extends ReplacementSpan {

    private int backgroundColor = 0;
    private int textColor = 0;

    public RoundBackgroundSpan(Context context) {
        super();
        backgroundColor = ContextCompat.getColor(context , R.color.amber_600);
        textColor = ContextCompat.getColor(context , R.color.white);
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        float newBottom = bottom - 2;
        float newTop = top + 2;
        RectF rect = new RectF(x , newTop , x + measureText(paint, text, start, end), newBottom );
        paint.setColor(backgroundColor);
        int CORNER_RADIUS = 8;
        canvas.drawRoundRect(rect, CORNER_RADIUS, CORNER_RADIUS, paint);
        paint.setColor(textColor);
        canvas.drawText(text, start, end, x , y, paint);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        return Math.round(paint.measureText(text, start, end));
    }

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

并在您的Spannable中使用它。

答案 4 :(得分:0)

基于@ evren-ozturk答案,没有textView链接和更好的版式支持

class RoundedBackgroundSpan(
    private val textColor: Int,
    private val backgroundColor: Int
) : ReplacementSpan() {

    private val additionalPadding = 4.toPx().toFloat()
    private val cornerRadius = 4.toPx().toFloat()

    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        val newTop = y + paint.fontMetrics.ascent
        val newBottom = y + paint.fontMetrics.descent
        val rect = RectF(x, newTop, x + measureText(paint, text, start, end) + 2 * additionalPadding, newBottom)
        paint.color = backgroundColor

        canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
        paint.color = textColor
        canvas.drawText(text, start, end, x + additionalPadding, y.toFloat(), paint)
    }

    override fun getSize(paint: Paint, text: CharSequence?, start: Int, end: Int, fm: FontMetricsInt?): Int {
        return (paint.measureText(text, start, end) + 2 * additionalPadding).roundToInt()
    }

    private fun measureText(paint: Paint, text: CharSequence, start: Int, end: Int): Float {
        return paint.measureText(text, start, end)
    }

    private fun Int.toPx(): Int {
        val resources = Resources.getSystem()
        val metrics = resources.displayMetrics
        return Math.round(this * (metrics.densityDpi / 160.0f))
    }
}

答案 5 :(得分:-1)

刚面临同样的问题,我发现这个答案对我很有效,也应该能够解决您的问题。 在 xml 中的 TextView 上进行配置:

<块引用>

android:lineSpacingMultiplier="2"

链接:How to add line spacing after every “\n” in a string in android?

已经 11 个月了,所以我希望你已经完成了它! 祝你好运!

答案 6 :(得分:-3)

您可以在XML文件中使用lineSpacingExtralineSpacingMultiplier。您可以在此处找到它:http://developer.android.com/reference/android/widget/TextView.html#attr_android%3alineSpacingExtra

对于背景颜色,您可以使用:

    <TextView
          android:background="#FFFF00" 
   />