获得WRAP_CONTENT高度

Fab*_*nti 11 java height animation android android-linearlayout

我的目的是让一个看不见的LinearLayout在点击特定按钮时显示为动画.为此,我将默认高度设置为WRAP_CONTENT,获取应用程序启动时的高度,将高度设置为0,并在单击按钮时启动动画.这是代码:

linearLayout.post(new Runnable() {
    @Override
    public void run(){
        height = linearLayout.getMeasuredHeight();
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 0));
    }
});


findViewById(R.id.btnOperator).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Animation ani = new ShowAnim(linearLayout, height/* target layout height */);
        ani.setDuration(1000/* animation time */);
        linearLayout.startAnimation(ani);

    }
});
Run Code Online (Sandbox Code Playgroud)

这项工作还不错,但我想做的不同.我希望默认高度为0,然后计算WRAP_CONTENT高度,并将其传递给:

Animation ani = new ShowAnim(linearLayout, height/* target layout height */);
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做?我搜索但发现了什么.

小智 19

试试这段代码:

linearLayout.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
height = linearLayout.getMeasuredHeight();
Run Code Online (Sandbox Code Playgroud)

  • 我认为这段代码不应该工作,因为 `measure` 接受 `MeasureSpec` 而不是 LayoutParam 宽度。来源:https://developer.android.com/reference/android/view/View.MeasureSpec (3认同)

Mic*_*sin 6

我认为 @tin-nguyen 提出的方法是错误的,因为View.measure方法Int按照MeasureSpec(这里是一个doc)接受。

所以,是的,您可以发送LayoutParams.WRAP_CONTENT,但这对您测量的视图没有多大意义。

如果视图的测量对您有用,那么当您发送时,WRAP_CONTENT请考虑这纯粹是运气。

所以你实际上需要调用:

val unspecifiedSpec = linearLayout.measure(
  /* widthMeasureSpec = */ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
  /* heightMeasureSpec = */ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
)
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你想模仿WRAP_CONTENT情况,这基本上意味着你想对视图说“请测量,我对你没有任何限制”。从UNSPECIFIED字面上看就是为了这个(文档链接)。