TextView中的Android多行

时间:2013-09-05 06:11:18

标签: android android-layout android-ui

enter image description here![图片] [2]我试过这段代码

private static class MySpan implements LineHeightSpan {
        private final int height;

        MySpan(int height) {
            this.height = height;
        }

        @Override
        public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
                FontMetricsInt fm) {
            fm.bottom += height;
            fm.descent += height;
        }
    }

    @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(), "Line 1 = 40\n", 40);
        appendLine(tv.getEditableText(), "Line 2 = 30\n", 30);
        appendLine(tv.getEditableText(), "Line 3 = 20\n", 20);
        appendLine(tv.getEditableText(), "Line 4 = 10\n", 10);

    }

    private void appendLine(Editable text, String string, int height) {
        final int start = text.length();
        text.append(string);
        final int end = text.length();
        text.setSpan(new MySpan(height), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

我正在尝试在 TextView 的行之间设置填充,但无法执行此操作。 如果我设置TextView的背景颜色,如何在TextView中区分多行。请指出我正确的方向。我想区分两行之间的颜色。你可以看到在这张图片中,它不起作用.. 我想要像第一张图像这样的东西,而我得到像第二张图像的输出.. 请帮我.. 提前谢谢

2 个答案:

答案 0 :(得分:1)

试试这种方式

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final TextView tv = new TextView(this);
    tv.setLineSpacing(2, 1); // UPDATE HERE
    setContentView(tv);

    tv.setText("Lines:\n", BufferType.EDITABLE);
    appendLine(tv.getEditableText(), "Line 1 = 40\n", 40);
    appendLine(tv.getEditableText(), "Line 2 = 30\n", 30);
    appendLine(tv.getEditableText(), "Line 3 = 20\n", 20);
    appendLine(tv.getEditableText(), "Line 4 = 10\n", 10);

}

答案 1 :(得分:0)

如果您想分割线条并以不同颜色显示它们,请参阅以下链接。

Split text from string

Apply color to specific text