简体   繁体   中英

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 . 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?

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

    }  
}); 

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.

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