Get what the WRAP_CONTENT height would be
Asked Answered
F

2

13

My purpose is to have an invisible LinearLayout that appear whit an animation when click on a specific button. To do this i have set the default height to WRAP_CONTENT, get the height when the app start, set the height to 0 and start the animation when i click on the button. Here is the code:

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);

    }
});

This work pretty good, but i want to do different. I want that the default height is 0, and then calculate what the WRAP_CONTENT height would be, and pass it to:

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

How could i do this? I searched but found anything.

Flirtatious answered 7/12, 2016 at 10:5 Comment(0)
M
25

Try this code:

linearLayout.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
height = linearLayout.getMeasuredHeight();
Mow answered 7/12, 2016 at 10:22 Comment(1)
I think this code isn't supposed to work as measure accepts MeasureSpec instead of LayoutParam width. Source: developer.android.com/reference/android/view/View.MeasureSpecTantalizing
T
6

I think the approach proposed by @tin-nguyen is wrong, as View.measure method accepts Int as per MeasureSpec (here is a doc).

So, yes, you can send LayoutParams.WRAP_CONTENT, but it will doesn't make much sense to the view you measuring.

If the measuring of the view is working for you, while you sent WRAP_CONTENT consider that pure luck.

So you actually need to call:

val unspecifiedSpec = linearLayout.measure(
  /* widthMeasureSpec = */ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
  /* heightMeasureSpec = */ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
)

In your case you want to imitate WRAP_CONTENT situation, which basically means you want to say to the view "Please measure, I don't have any limitations for you". And UNSPECIFIED is literally for that (doc link).

Tantalizing answered 22/9, 2023 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.