突出显示TextView中的文本行,包括所有宽度 [英] Highlight text row in TextView including all width
问题描述
我已经查看了如何使用 Spannable
类在 TextView
中突出显示某些文本的一些解决方案。但它只允许突出显示由字符组成的片段。如果我想突出显示包含 TextView
的宽度的文本行,但是此行中的文本不会填满整个视图的宽度,该怎么办?
I have already looked through some solutions of how to highlight some text in TextView
using Spannable
class. But it only allows to highlight a snippet which consists of characters. And what if I want to highlight a text row including TextView
's width, but a text in this row doesn't fill whole view's width?
如果有人有这种情况的经验,我很乐意接受建议。
If anybody had an experience in such cases I would be glad to take an advice.
好的,我希望以下图片可以明确我的目标。
Ok, I hope following images will bring some clarity of my aim.
这是我可以用实现的
:
这就是我想要的:
我真的希望它很清楚。
推荐答案
可能有一种更简单的方法可以执行此操作,但我相信您需要实现一个实现LineBackgroundSpan的类来执行您想要的操作。下面是一些示例代码:
There might be an easier way to do this, but I believe you will need to implement a class that implements LineBackgroundSpan to do what you want. Here's some sample code:
public class MyActivity extends Activity {
private static class MySpan implements LineBackgroundSpan {
private final int color;
public MySpan(int color) {
this.color = color;
}
@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 lnum) {
final int paintColor = p.getColor();
p.setColor(color);
c.drawRect(new Rect(left, top, right, bottom), p);
p.setColor(paintColor);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TextView tv = new TextView(this);
setContentView(tv);
tv.setText("Lines:\n", BufferType.EDITABLE);
appendLine(tv.getEditableText(), "123456 123 12345678\n", Color.BLACK);
appendLine(tv.getEditableText(), "123456 123 12345678\n", Color.RED);
appendLine(tv.getEditableText(), "123456 123 12345678\n", Color.BLACK);
}
private void appendLine(Editable text, String string, int color) {
final int start = text.length();
text.append(string);
final int end = text.length();
text.setSpan(new MySpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
这篇关于突出显示TextView中的文本行,包括所有宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!