Highlight text row in TextView including all width
android, java, textview
Solution
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);
}
}
Problem
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. Update: Ok, I hope following images will bring some clarity of my aim. This is waht I can achieve using `Spannable`: And this is what I want: I really hope that it's clear.