在onCreate()里是获取不到控件的width,height的,这个时候控件都没有measure,layout完毕,所以获取到的结果都是0。要获取控件的宽度、高度必须在measure、layout过程完毕之后。
有2种方法:
1.用ViewTreeObserver坚挺控件的状态 :
ViewTreeObserver vto = mBtnSend.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int height = mBtnSend.getMeasuredHeight();
int width = mBtnSend.getMeasuredWidth();
System.out.println("height:" + height + " " + "width:" + width);
}
});
2.在Activity里重写方法
public void onWindowFocusChanged(boolean hasFocus);
有2种方法:
1.用ViewTreeObserver坚挺控件的状态 :
ViewTreeObserver vto = mBtnSend.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int height = mBtnSend.getMeasuredHeight();
int width = mBtnSend.getMeasuredWidth();
System.out.println("height:" + height + " " + "width:" + width);
}
});
2.在Activity里重写方法
public void onWindowFocusChanged(boolean hasFocus);
在窗口获得焦点的时候
获取到控件的getWidth(),getHeight()获取宽度和高度。