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

前端 未结 1 439
灰色年华
灰色年华 2020-12-17 03:42

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

相关标签:
1条回答
  • 2020-12-17 03:50

    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();  
    
        }  
    }); 
    
    0 讨论(0)
提交回复
热议问题