如何获得TextView中的行数? [英] How to get number of lines of TextView?
问题描述
我希望得到一个文本视图的行数
I want to get the number of lines of a text view
textView.setText("Test line 1 Test line 2 Test line 3 Test line 4 Test line 5.............")
textView.getLineCount();
总是返回零
然后我也曾尝试:
ViewTreeObserver vto = this.textView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = textView.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
System.out.println(": " + textView.getLineCount());
}
});
它返回的准确输出。
It returns the exact output.
但是,这仅适用于静态布局。
But this works only for a static layout.
当我膨胀的布局动态此不再工作了。
When I am inflating the layout dynamically this doesn't work anymore.
我怎么能找到一个TextView行的编号?
How could I find the number of line in a TextView?
推荐答案
正如本<一个href="http://stackoverflow.com/questions/3528790/textview-getlinecount-always-0-in-android">post,
getLineCount()
后才会给你行的正确数量
一个布局传递。
getLineCount()
will give you the correct number of lines only after a layout pass.
这意味着你需要渲染的的TextView
之前,先调用 getLineCount()
方法。
It means that you need to render the TextView
first before invoking the getLineCount()
method.
这篇关于如何获得TextView中的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!