这是一个适用于 Spannable 的解决方案,如果左右太宽,它们将在同一条线上重叠。由于使用 spannable 执行 Left/Right 技巧需要在 Left 和 Right 之间换行,我的解决方法是添加一个 spannable,将一个换行的行高减少为零(即重叠行),然后在之后恢复正常行高那。
String fullText = leftText + "\n " + rightText; // only works if linefeed between them! "\n ";
int fullTextLength = fullText.length();
int leftEnd = leftText.length();
int rightTextLength = rightText.length();
final SpannableString s = new SpannableString(fullText);
AlignmentSpan alignmentSpan = new AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE);
s.setSpan(alignmentSpan, leftEnd, fullTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(new SetLineOverlap(true), 1, fullTextLength-2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(new SetLineOverlap(false), fullTextLength-1, fullTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
我们有处理重叠线的小程序:
private static class SetLineOverlap implements LineHeightSpan {
private int originalBottom = 15; // init value ignored
private int originalDescent = 13; // init value ignored
private Boolean overlap; // saved state
private Boolean overlapSaved = false; // ensure saved values only happen once
SetLineOverlap(Boolean overlap) {
this.overlap = overlap;
}
@Override
public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
Paint.FontMetricsInt fm) {
if (overlap) {
if (!overlapSaved) {
originalBottom = fm.bottom;
originalDescent = fm.descent;
overlapSaved = true;
}
fm.bottom += fm.top;
fm.descent += fm.top;
} else {
// restore saved values
fm.bottom = originalBottom;
fm.descent = originalDescent;
overlapSaved = false;
}
}
}