简体   繁体   English

Android - 获取设置为wrap_content的按钮的宽度

[英]Android - getting the width of a button which is set to wrap_content

I am trying to get the width of a button whose android:layout_width is set to wrap_content . 我试图获得一个按钮的宽度,其android:layout_width设置为wrap_content When I try to do that in onCreate() using getMeasuredWidth() , I get a value of zero because I think the view is not ready yet. 当我尝试使用getMeasuredWidth()onCreate()执行此操作时,我得到零值,因为我认为视图还没有准备好。

When should I get the width then? 我什么时候应该得到宽度呢? Is there any listener I can hook to when view is done initializing? 在查看初始化时,是否有任何可以挂钩的监听器?

You can add a tree observer to the layout. 您可以将树观察器添加到布局中。 This should return the correct width and height. 这应该返回正确的宽度和高度。 onCreate is called before the layout of the child views are done. 在完成子视图的布局之前调用onCreate。 So the width and height is not calculated yet. 所以宽度和高度尚未计算。 To get the height and width. 获得高度和宽度。 Put this on the onCreate method 把它放在onCreate方法上

LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID); 
ViewTreeObserver vto = layout.getViewTreeObserver();  
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {  
    @Override  
    public void onGlobalLayout() {  
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);  
        int width  = layout.getMeasuredWidth(); 
        int height = layout.getMeasuredHeight();  

    }  
}); 

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

相关问题 在Android中如何获取设置为Wrap_Content的Textview的宽度 - In Android how to get the width of the Textview which is set to Wrap_Content 如何在 GridLayout 中将我的按钮宽度设置为“wrap_content”? - How to set my button width to "wrap_content" inside the GridLayout? android:相对布局宽度wrap_content - android : Relative layout width wrap_content 当宽度为 wrap_content 时,设置按钮的高度等于宽度 - Set button's height equal to width when width is wrap_content wrap_content 在按钮高度 android 下不起作用 - wrap_content is not working in button height android Android:将 Horizo​​ntalGridView 设置为 wrap_content? - Android: Set HorizontalGridView to wrap_content? Android Wrap_Content - Android Wrap_Content 当 CoordinatorLayout 的宽度设置为 wrap_content 时,CoordinatorLayout 隐藏了一半的浮动操作按钮 - CoordinatorLayout is hiding half of the floating action button when CoordinatorLayout 's width is set to wrap_content Android-ImageView-多屏支持-将高度/宽度设置为dp还是match_parent / wrap_content? - Android - ImageView - Multiple Screen Support - Set height/width as dp or match_parent/wrap_content? 如何知道小部件的宽度是否设置为wrap_content - How to know if widgets width is set to wrap_content
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM