Android RecyclerView中TextView上的getLineCount()返回零

Android RecyclerView中TextView上的getLineCount()返回零,android,android-recyclerview,android-adapter,Android,Android Recyclerview,Android Adapter,我有一个RecyclerView,我需要能够检查TextView中有多少行 我正在使用getLineCount()获取行数,但当我打开应用程序时,它将返回零(即使TextView中有10多行) 经过一些测试,我发现如果我在RecyclerView中向下滚动几个项目,然后再向上滚动到顶部,它将返回正确的行数 以下是我的RecyclerView适配器的相关部分: public void onBindViewHolder(ViewHolder holder, int position) { P

我有一个RecyclerView,我需要能够检查TextView中有多少行

我正在使用
getLineCount()
获取行数,但当我打开应用程序时,它将返回零(即使TextView中有10多行)

经过一些测试,我发现如果我在RecyclerView中向下滚动几个项目,然后再向上滚动到顶部,它将返回正确的行数

以下是我的RecyclerView适配器的相关部分:

public void onBindViewHolder(ViewHolder holder, int position) {
    Post post = data.get(position);

    holder.textView.setText(post.getDescription());

    int linecount = holder.textView.getLineCount();

    Log.d(TAG, "Number of lines is " + linecount);
}

我能做些什么来解决这个问题?

在询问需要多少行之前,您需要让
文本视图绘制文本

试一试


在询问需要多少行之前,需要让
TextView
绘制文本

试一试


您需要在
TextView
上使用
OnGlobalLayoutListener
来回调
onLayout()
调用:

public void onBindViewHolder(ViewHolder holder, int position) {
    Post post = data.get(position);
    holder.textView.setText(post.getDescription());

    holder.textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            holder.textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            int linecount = holder.textView.getLineCount();
            Log.d(TAG, "Number of lines is " + linecount);
        }
    });
}

您需要在
TextView
上使用
OnGlobalLayoutListener
来回调
onLayout()
调用:

public void onBindViewHolder(ViewHolder holder, int position) {
    Post post = data.get(position);
    holder.textView.setText(post.getDescription());

    holder.textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            holder.textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            int linecount = holder.textView.getLineCount();
            Log.d(TAG, "Number of lines is " + linecount);
        }
    });
}

这将仅对渲染的初始项激发…不会对回收的项激发。。最好在PreDrawListener上使用此选项仅对渲染的初始项激发…不会对回收的项激发。。我最好在predrawlistener上使用它