问题描述
是否可以为 TextView
的每个文本行定义单独的行距?
Is it possible to define individual line spacings for each text line of a TextView
?
例子:
TextView tv = new TextView(context);
tv.setText("line1
line2
line3");
setLineSpacing(float add, float mult)
方法定义了TextView
的所有文本行的行距.我想在 line1 和 line2 之间定义另一个行距,在 line2 和 line3 之间定义一个不同的行距.
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
接口来实现.这是一个关于如何执行此操作的快速而肮脏的示例代码:
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:
", BufferType.EDITABLE);
appendLine(tv.getEditableText(), "Line 1 = 40
", 40);
appendLine(tv.getEditableText(), "Line 2 = 30
", 30);
appendLine(tv.getEditableText(), "Line 3 = 20
", 20);
appendLine(tv.getEditableText(), "Line 4 = 10
", 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);
}
}
这篇关于每行的单独行距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!