突出显示TextView中的文本行,包括所有宽度

teo*_*tik 2 java android textview

我已经查看了如何在TextView使用Spannable类中突出显示某些文本的一些解决方案.但它只允许突出显示由字符组成的片段.如果我想要突出显示包含TextView宽度的文本行,但此行中的文本不会填满整个视图的宽度,该怎么办?

如果有人在这种情况下有经验,我很乐意接受建议.

更新:

好的,我希望以下图片可以清晰地表达我的目标.

这是我可以实现的Spannable:

在此输入图像描述

这就是我想要的:

在此输入图像描述

我真的希望它很清楚.

Joe*_*Joe 8

可能有一种更简单的方法可以做到这一点,但我相信你需要实现一个实现LineBackgroundSpan的类来做你想要的.这是一些示例代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)