要获取控件的宽度、高度必须在measure、layout过程完毕之后,有三种方法:
1.
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);
在窗口第一次获得焦点的时候,肯定能获取到控件的width,height。
3.int intw=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
int inth=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
textView.measure(intw, inth);
int intwidth = textView.getMeasuredWidth();
int intheight = textView.getMeasuredHeight();