考虑这个简单的例子:
我有一个这样的单行文本:"Hello“
我想用StaticLayout来测量这个文本。所以我写了这样的东西:
StaticLayout layout = new StaticLayout("Hello", myTextView.getPaint(), myTextView.getWidth(), Layout.Alignment.NORMAL, 1, lineSpace, false);在上面的代码中,我更改了for循环中的lineSpace变量,每次记录布局的高度:
for(int lineSpace=0; lineSpace<20;lineSpace++){
StaticLayout layout = new StaticLayout("Hello", myTextView.getPaint(), myTextView.getWidth(), Layout.Alignment.NORMAL, 1, lineSpace, false);
Log.d("TAG", "layout height: " + layout.getHeight());
}当我在使用android M布局的设备上运行这段代码时,高度不会随着lineSpace的多个值而改变。但在较低的android版本中,布局的高度会随着行距的变化而变化。
不过,当文本超过一行时,StaticLayout会考虑两行之间的行距。但看起来Android M没有考虑最后一行的行距,但Android版本较低的版本考虑了。
我的问题是:在什么版本的android StaticLayout之后,考虑将行空间作为最后一行?我可以写这样的东西吗:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// in this version StaticLayout don't consider line space for last line
} else {
// in this version StaticLayout consider line space for last line
}发布于 2017-01-18 22:03:15
我在源代码中做了一些快速挖掘,似乎this part是罪魁祸首:
if (needMultiply && !lastLine) {
double ex = (below - above) * (spacingmult - 1) + spacingadd;
if (ex >= 0) {
extra = (int)(ex + EXTRA_ROUNDING);
} else {
extra = -(int)(-ex + EXTRA_ROUNDING);
}
} else {
extra = 0;
}较早的版本缺少!lastLine条件,因此也在最后一行添加了空格。
这个条件是在this commit中添加的,如果我的github foo没有让我失望的话,从Android5开始应该包括它。
显然,就像提交提到的那样,这只影响单行文本,对于多行文本,高度似乎计算正确。因此,一个简单的解决方法可能是检查文本是否只有一行(使用getLineCount()),以及Android版本是否小于5,如果是,则减去行距一次。
https://stackoverflow.com/questions/41719899
复制相似问题