渲染前测量多行TextView的高度

Sha*_*hai 5 java android textview

我已经尝试到了什么:

  1. 呼唤 measure()

    tv.measure(0, 0);
    int height = tv.getMeasuredHeight();
    
    Run Code Online (Sandbox Code Playgroud)
  2. measure()以指定的尺寸/模式进行呼叫

    int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(99999, View.MeasureSpec.AT_MOST);
    int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    tv.measure(widthMeasureSpec, heightMeasureSpec);
    int height = tv.getMeasuredHeight();
    
    Run Code Online (Sandbox Code Playgroud)
  3. 呼唤 getTextBounds()

    Rect bounds = new Rect();
    tv.getPaint().getTextBounds(tv.getText().toString(), 0, tv.getText().length(), bounds);
    int height = bounds.height();
    
    Run Code Online (Sandbox Code Playgroud)
  4. 先打电话measure()再打电话getTextBounds()

  5. 呼唤 getLineCount() * getLineHeight()

似乎没有任何工作。它们都返回不正确的值(容器视图的高度不正确-太小或太大)

关于如何计算这个简单事情的想法?

Fer*_*nch 5

您需要指定可用宽度,以便正确计算高度。

注意:如果您只需要获取已绘制视图的高度,请使用ViewTreeObserver. 在这种情况下要考虑的事情请参阅此问题

这就是为什么我这样做,在一段代码中,我想将视图从隐藏缩放到其所需的全部高度:

int availableWidth = getParentWidth(viewToScale);

int widthSpec = View.MeasureSpec.makeMeasureSpec(availableWidth, View.MeasureSpec.AT_MOST);
int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

viewToScale.measure(widthSpec, heightSpec);
int measuredHeight = viewToScale.getMeasuredHeight();
// Offtopic: Now I animate the height from 1 to measuredHeight (0 doesn't work)
Run Code Online (Sandbox Code Playgroud)

您可以通过availableWidth自己,但我从父母计算:

private int getParentWidth(View viewToScale)
{
    final ViewParent parent = viewToScale.getParent();
    if (parent instanceof View) {
        final int parentWidth = ((View) parent).getWidth();
        if (parentWidth > 0) {
            return parentWidth;
        }
    }

    throw new IllegalStateException("View to scale must have parent with measured width");
}
Run Code Online (Sandbox Code Playgroud)


EE6*_*E66 1

你在哪里调用这些方法?完成您想要做的事情的最佳方法是使用 ViewTreeObserver 并添加 onPreDrawListener。看看这个我想它会有所帮助