今天遇到获取textview 的文字行数的需求,在此记录下。 我们在开发中,经常需要获取textview 的行数,可是发现在 textview.setText() 之后,再调用 getLineCount() 方法返回的是0,以下是源码的注释,意思就是如果这个textview 还没有被画出来,则返回的是0。
/**
* Return the number of lines of text, or 0 if the internal Layout has not
* been built.
*/
public int getLineCount() {
return mLayout != null ? mLayout.getLineCount() : 0;
}
所以,我们需要异步执行下,拿到lineCount,如下即可。
post(new Runnable() {
@Override
public void run() {
int lineCount = mTextView.getLineCount();
}
});
类似的,我们在用 SwipeRefreshLayout
的时候,如果需要刷新,也同样需要异步,这些都需要注意下