??一般情況下画拾,TextView的行數(shù)要等到其布局完成后才能獲取到灼狰,否則如果直接調(diào)用textView.getLineCount()
函數(shù)獲取到的結(jié)果只會為0阳距,那能不能提前獲取到TextView的行數(shù)呢,當然是肯定的糖声。TextView內(nèi)部的換行是通過一個StaticLayout的類來處理的豹悬,而且我們調(diào)用的getLineCount()方法最后也是調(diào)用的StaticLayout類中的getLineCount()方法葵陵,所以我們只需要創(chuàng)建一個和TextView內(nèi)部一樣的StaticLayout就可以了,然后調(diào)用staticLayout.getLineCount()
方法就可以獲取到和當前TextView行數(shù)一樣的值了瞻佛,但要注意一個前提條件就是保證TextView的width是已知的脱篙,否則也無法獲取到正確的行數(shù)。
/**
* 提前獲取textview行數(shù)
*/
public class TextViewLinesUtil {
public static int getTextViewLines(TextView textView, int textViewWidth) {
int width = textViewWidth - textView.getCompoundPaddingLeft() - textView.getCompoundPaddingRight();
StaticLayout staticLayout;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
staticLayout = getStaticLayout23(textView, width);
} else {
staticLayout = getStaticLayout(textView, width);
}
int lines = staticLayout.getLineCount();
int maxLines = textView.getMaxLines();
if (maxLines > lines) {
return lines;
}
return maxLines;
}
/**
* sdk>=23
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private static StaticLayout getStaticLayout23(TextView textView, int width) {
StaticLayout.Builder builder = StaticLayout.Builder.obtain(textView.getText(),
0, textView.getText().length(), textView.getPaint(), width)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setTextDirection(TextDirectionHeuristics.FIRSTSTRONG_LTR)
.setLineSpacing(textView.getLineSpacingExtra(), textView.getLineSpacingMultiplier())
.setIncludePad(textView.getIncludeFontPadding())
.setBreakStrategy(textView.getBreakStrategy())
.setHyphenationFrequency(textView.getHyphenationFrequency())
.setMaxLines(textView.getMaxLines() == -1 ? Integer.MAX_VALUE : textView.getMaxLines());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setJustificationMode(textView.getJustificationMode());
}
if (textView.getEllipsize() != null && textView.getKeyListener() == null) {
builder.setEllipsize(textView.getEllipsize())
.setEllipsizedWidth(width);
}
return builder.build();
}
/**
* sdk<23
*/
private static StaticLayout getStaticLayout(TextView textView, int width) {
return new StaticLayout(textView.getText(),
0, textView.getText().length(),
textView.getPaint(), width, Layout.Alignment.ALIGN_NORMAL,
textView.getLineSpacingMultiplier(),
textView.getLineSpacingExtra(), textView.getIncludeFontPadding(), textView.getEllipsize(),
width);
}
}