如何增加新文本段落的编辑文本中的行高



我有一个EditText,我希望行之间有更大的空间,但只有当用户通过按回车键创建新行时。 我不希望文本自行返回时空间更大,因为行太长。

我尝试使用lineSpacingExtra但不幸的是,它在两种情况下都会改变行高。

感谢您的帮助。

您可以附加一个 TextWatcher 并从提供的回调中处理您的逻辑。

让你的活动/片段实现文本观察器。

实现回调。

在您的活动/片段中保留一个布尔变量,以指示行距是否处于"大"状态。

private boolean largeLines = false;
private EditText inputText;
@Override
public void onCreate(Bundle savedInstanceState) {
inputText = (EditText) findViewById(R.id.input_text);
inputText.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Check if the text contains a new line character
if (s.toString().contains("n")) {
// If we haven't already, increase the line spacing by 1.2x
if (!largerLines) {
inputText.setLineSpacing(0, 1.2f);
largerLines = true;
}
}
// If there is no new line character & the line spacing is
// large, make it smaller again by 0.8x
else if (largerLines) {
inputText.setLineSpacing(0, 0.8f);
largerLines = false;
}
}
@Override
public void afterTextChanged(Editable s) {
// Do nothing
}

我找到了一种使用跨度的方法。 每次我检测到插入的""(使用 TextWatcher)时,我都会用 TopPrideSpan 包装我的新行。

class TopPaddedSpan implements LineHeightSpan {
private boolean initialised = false;
private int originalAscent;
private int increasedAscent;
@Override
public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v, Paint.FontMetricsInt fm) {
if (!initialised) {
originalAscent = fm.ascent;
increasedAscent = Math.round(fm.ascent * 1.6f);
initialised = true;
}
if (spanstartv == v) { // First drawn line
fm.ascent = increasedAscent;
} else { // Any other lines
fm.ascent = originalAscent;
}
}
}

希望对某人有帮助

最新更新