获取 WRAP_CONTENT 高度是多少

问题描述 投票:0回答:2

我的目的是拥有一个不可见的 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);

    }
});

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

Animation ani = new ShowAnim(linearLayout, height/* target layout height */);

我怎样才能做到这一点?我搜索过但没有找到任何东西。

java android animation height android-linearlayout
2个回答
28
投票

试试这个代码:

linearLayout.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
height = linearLayout.getMeasuredHeight();

0
投票

我认为@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)
)

在你的情况下,你想模仿

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

© www.soinside.com 2019 - 2024. All rights reserved.