简体   繁体   English

android-获取以编程方式创建的视图的估计高度

[英]android - get estimated height of a programmatically created view

How to get programmatically created RelativeLayout's height after adding all the views in it (ie, when it really can be measured)? 在其中添加所有视图后(即何时真正可以测量),如何以编程方式创建RelativeLayout的 高度 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. 我以编程方式创建了应该是该RL子级按钮的Button,设置其边距和对齐方式,并将其添加到RL中,以便可以测量RL的高度。 Ordinary rl.getHeight() returns 0. I used this code: 普通的rl.getHeight()返回0。我使用了以下代码:

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. 在Nexus 5(API 23)上一切正常,但是在另一台使用API​​ 17的设备上(我记得是4.2或其他),它会抛出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. PS OnGlobalLayoutListener和OnPreDrawListener不好,因为在调用setParams(...)并将RL添加到外部布局之前,需要测量高度。

You can use a GlobalLayoutListener or an OnPreDrawListener to programmatically find a views height at runtime. 您可以使用GlobalLayoutListener或OnPreDrawListener在运行时以编程方式查找视图高度。 Refer to this answer for an example: https://stackoverflow.com/a/6569243/4898635 请参考此答案以获取示例: https : //stackoverflow.com/a/6569243/4898635

Make sure to remove the listener after you have your height however, otherwise it will continuously be called. 但是,一定要在身高升高后移开监听器,否则它将被连续调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM