TextView的背景颜色和行间距行间、颜色、背景、TextView

2023-09-07 12:20:22 作者:时光凉透初时模样

我想显示像下面的文字...

我的代码如下:

  SpannableString STEXT =新SpannableString(文本);
sText.setSpan(新BackgroundColorSpan(Color.YELLOW),0,sText.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

holder.txtText.setLineSpacing(0,1.5F);
textView.setText(STEXT);
 

解决方案

试试这个。 创建自定义的TextView和覆盖方法平局(画布油画)。

 公共类BgColorTextView扩展TextView的{
    公共BgColorTextView(上下文的背景下){
        超(上下文);
    }

    公共BgColorTextView(上下文的背景下,ATTRS的AttributeSet){
        超(背景下,ATTRS);
    }

    公共BgColorTextView(上下文的背景下,ATTRS的AttributeSet,诠释defStyleAttr){
        超(背景下,ATTRS,defStyleAttr);
    }

    公共BgColorTextView(上下文的背景下,ATTRS的AttributeSet,诠释defStyleAttr,诠释defStyleRes){
        超(背景下,ATTRS,defStyleAttr,defStyleRes);
    }

    @覆盖
    公共无效画(油画画布){
        INT lineCount = getLayout()getLineCount()。
        矩形RECT =新的矩形();
        涂料粉刷=新的油漆();
        paint.setColor(getResources()的getColor(R.color.YOUR_CUSTOM_COLOR));
        的for(int i = 0; I< lineCount;我++){
            rect.top =(getLayout()getLineTop(i)中。);
            。rect.left =(int)的getLayout()getLineLeft(ⅰ);
            。rect.right =(int)的getLayout()getLineRight(ⅰ);
            rect.bottom =(int)的(getLayout()getLineBottom(ⅰ) - (第(i + 1 == lineCount)0:?getLayout()getSpacingAdd()));

            canvas.drawRect(矩形,油漆);
        }
        super.draw(画布);
    }
}
 

如何简单优雅的适配 textview 行间距

I'd like to show the text like the below...

My coding is the following:

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);

解决方案

try this. Create custom TextView and override method draw(Canvas 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);
    }
}