我有一个TextView,getLayout返回null。 根据文档,这是“正常”,因为在此之前,我将其添加到布局中,然后更改其宽度。
如何避免这种情况?
(我尝试使用OnGlobalLayoutListener,然后等待它的全宽,但它并不总是有效)
编辑: 我从getView()中的列表适配器调用:
drawArticle(article, true);
这是drawArticle()方法:
TextView txt;
Spanned text;
private void drawArticle(final Article article, boolean first) {
if(first){
text = Html.fromHtml(article.content);
} else {
text = Html.fromHtml(getInvisibleText(txt));
}
txt = createTextView();
txt.setText(text);
layout.addView(txt);
vto = txt.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
txt.getViewTreeObserver().removeGlobalOnLayoutListener(this);
String inVisibleText = getInvisibleText(txt);
if (inVisibleText != null && !inVisibleText.isEmpty()) {
drawArticle(article, false);
}
}
});
}
和
private String getInvisibleText(final TextView textView) {
Layout staticLayout = null;
String toDislay = "";
int height = textView.getHeight();
int scrollY = textView.getScrollY();
staticLayout = textView.getLayout();
int lastVisibleLineNumber = staticLayout.getLineForVertical(scrollY+height);
int start = staticLayout.getLineEnd(lastVisibleLineNumber);
int end = staticLayout.getLineEnd(textView.getLineCount()-1);
toDislay = textView.getText().toString().substring(start, end);
return toDislay;
}
这是假设将非常长的文本设置为文本视图,然后获取未显示的内容以递归方式放入其他文本视图