4

我有一个 getLayout 返回 null 的 TextView。根据文档,这是“正常的”,因为就在之前,我将它添加到布局中,然后它改变了它的宽度。

如何避免这种情况?

(我尝试使用 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;
}

这是假设将很长的文本设置到文本视图中,然后将不显示的内容递归地放入其他文本视图中

4

0 回答 0