0

How to get programmatically created RelativeLayout's height after adding all the views in it (i.e., when it really can be measured)? I programmatically created Buttons that should be children for that RL, set their margins and alignment, added them to the RL, so RL's height can be measured. Ordinary rl.getHeight() returns 0. I used this code:

rl.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); 
int rlHeight=rl.getMeasuredHeight();

And on Nexus 5 (API 23) everything's ok, but on the other device with API 17 (as I remember, 4.2 or something) it throws NPE. What to do?

P.S. OnGlobalLayoutListener and OnPreDrawListener are not ok, because I need the height to be measured before calling setParams(...) and adding the RL to outer layout.

Justin McGuire
  • 365
  • 1
  • 5
  • 18
  • 1
    Possible duplicate of [Determining the size of an Android view at runtime](http://stackoverflow.com/questions/3779173/determining-the-size-of-an-android-view-at-runtime) – Dom Mar 19 '16 at 08:56

1 Answers1

0

You can use a GlobalLayoutListener or an OnPreDrawListener to programmatically find a views height at runtime. Refer to this answer for an example: https://stackoverflow.com/a/6569243/4898635

Make sure to remove the listener after you have your height however, otherwise it will continuously be called.

Community
  • 1
  • 1
Dom
  • 8,222
  • 2
  • 15
  • 19
  • In my case it doesn't work ok (all of the "heights" return 0) 'cause I need to get height of my RLs (I create several different ones in "for") before setting LayoutParams to my RelativeLayout and adding it to the outer layout. Could you please provide some other solution? – Justin McGuire Mar 19 '16 at 17:25
  • At what part of the lifecycle do you add this relative layout? Do you add it in `onCreateView`/`onCreate` or do you add it after a user event? – Dom Mar 19 '16 at 23:15
  • I do it in onCreate. Actually I've already found something like a solution, I just put "outerLayout.addView(rl);" above the code given in my initial question, and then after I've measured I set margins and set layoutparams to that just-added RL. Now it works ok on pre-Marshmallow devices too. Not sure it's the best solution though :) – Justin McGuire Mar 19 '16 at 23:22