Android - 获取设置为 wrap_content 的按钮的宽度 [英] Android - getting the width of a button which is set to wrap_content

查看:32
本文介绍了Android - 获取设置为 wrap_content 的按钮的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取将 android:layout_width 设置为 wrap_content 的按钮的宽度.当我尝试在 onCreate() 中使用 getMeasuredWidth() 执行此操作时,我得到的值为零,因为我认为视图尚未准备好.

I am trying to get the width of a button whose android:layout_width is set to 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.

那我什么时候应该得到宽度?当视图完成初始化时,是否有任何我可以挂钩的侦听器?

When should I get the width then? Is there any listener I can hook to when view is done initializing?

推荐答案

您可以向布局添加树观察器.这应该返回正确的宽度和高度.在完成子视图的布局之前调用 onCreate.所以宽度和高度还没有计算出来.获取高度和宽度.把这个放在 onCreate 方法上

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. So the width and height is not calculated yet. To get the height and width. Put this on the onCreate method

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

    }  
}); 

这篇关于Android - 获取设置为 wrap_content 的按钮的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆