这是一个与Spantable一起使用的解决方案,如果右侧和左侧太宽,它们将在同一条线上重叠。由于要使用可跨越进行左/右技巧需要在左和右之间使用换行符,因此我的修复方法是添加一个可跨越项,该可跨越项将一个换行符的行高减少到零(即重叠的行),然后恢复正常的行高。
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;
}
}
}