具有背景颜色和行距的 TextView

编程入门 行业动态 更新时间:2024-10-08 04:31:25
本文介绍了具有背景颜色和行距的 TextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想显示如下文本...

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

我的编码如下:

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

推荐答案

试试这个.创建自定义 TextView 并覆盖方法 draw(Canvas canvas).

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

更多推荐

具有背景颜色和行距的 TextView

本文发布于:2023-11-25 21:01:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631329.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:行距   颜色   背景   TextView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!