Android layoutParams getWidth()getHeight()

BLO*_*OKE 2 android android-layout

这些方法在动态检索时返回正确的值,例如.在onCreate()中,但唯一的例外是当xml布局文件中的维度未定义时,如'wrap content'等.有没有办法检索这些值呢?

ble*_*enm 7

这应该返回正确的宽度和高度.在完成子视图的布局之前调用onCreate.所以宽度和高度尚未计算.获得高度和宽度.把它放在onCreate方法上

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

    } 
});
Run Code Online (Sandbox Code Playgroud)