个别行间距为每个线行间、个别

由网友(知名叔叔)分享简介:是否有可能定义单个行间距为每个文本行的TextView ?Is it possible to define individual line spacings for each text line of a TextView?例如:TextView tv = new TextView(context);tv.se...

是否有可能定义单个行间距为每个文本行的TextView

Is it possible to define individual line spacings for each text line of a TextView?

例如:

TextView tv = new TextView(context);
tv.setText("line1nline2nline3");

方法 setLineSpacing(浮点加法,浮点MULT)定义行间距,所有文本行的的TextView 。我想定义一号线和2号线和2号线和3号线之间的不同行距之间的另一条线间距。

The method setLineSpacing(float add, float mult) defines the line spacings for all text lines of the TextView. I would like to define another line spacing between line1 and line2 and a different line spacing between line2 and line3.

任何想法如何做到这一点?

Any ideas how to do this ?

做了spannable提供一个解决方案?

Does a spannable provide a solution ?

推荐答案

是的,你可以利用 LineHeightSpan 界面做到这一点。下面是关于如何做到这一点的快速和肮脏的样品code:

Yes, you can do it by utilizing the LineHeightSpan interface. Here's a quick and dirty sample code on how to do this:

public class MyActivity extends Activity {

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

}
阅读全文

相关推荐

最新文章