How to get programmatically created RelativeLayout's height after adding all the views in it (ie, 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?
PS OnGlobalLayoutListener and OnPreDrawListener are not ok, because I need the height to be measured before calling setParams(...) and adding the RL to outer layout.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.