我们都知道,View的onMeasure()方法是在onCreate()方法之后调用,我们在onCreate()中获取控件的width和height总是为0。 解决这个问题,有以下几种方法:
复制 // 根据提供的大小值和模式创建一个测量值(格式)
int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
button.measure(w, h); // 让button先mesure
int width =button.getMeasuredWidth();
Log.i(TAG, "-=-=-=-=-= width" + width);
复制 final ViewTreeObserver vto = button.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
// 注意要移出监听,否则会多次调用,因为是view tree全局监听,每个子view的变化都会触发这个监听。
button.getViewTreeObserver().removeOnPreDrawListener(this);
int width = button.getWidth();
int measuredWidth = button.getMeasuredWidth();
Log.i(TAG, "\n\n" + "draw ===== width:" + width + "," + "measureWidth" +
measuredWidth);
return true;
}
});
复制 vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
button.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int width = button.getWidth();
int measuredWidth = button.getMeasuredWidth();
Log.i(TAG, "\n\n" + "layout ===== width:" + width + "," + "measureWidth" +
measuredWidth);
}
});