因为Activity的生命周期回调和view的measure过程不是同步执行的,所以无法在activity的onCreate、onStart和onResume里面准确的获取view的宽和高,可以通过以下四个方法来获取:
1.Activity/View#onWindowFocusChanged
/**
* 该方法会被多次调用,获取焦点和失去焦点,这里我们一般应该都只关心获取焦点的时候
* @param hasFocus
*/
@Overridepublic void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
int height = mIvTarget.getMeasuredHeight();
int width = mIvTarget.getMeasuredWidth();
mTvFocus.setText("onWindowFocusChanged-----宽度:" + width + ",高度:" + height);
}
}
2.view.post(runnable)
/**
* view.post(runnable)
* 该方法将一个runnable投递到消息队列的尾部,然后等待Looper 调用此方法对的时候,View已经初始化好了
*/
private void viewPost() {
mIvTarget.post(new Runnable() {
@Override
public void run() {
int height = mIvTarget.getMeasuredHeight();
int width = mIvTarget.getMeasuredWidth();
mTvPost.setText("view.post(runnable)-----宽度:" + width + ",高度:" + height);
}
});
}
3.ViewTreeObserver
/**
*viewtreeobserver:通过监听OnGlobalLayoutListener这个接口,当view树的状态发生改变或者view树内部的可见性发生改变的时候,将被回调,这里会被多次调用
*/
private void viewTreeObserver() {
mIvTarget.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mIvTarget.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int width = mIvTarget.getMeasuredWidth();
int height = mIvTarget.getMeasuredHeight();
mTvTree.setText("ViewTreeObserver-----宽度:" + width + ",高度:" + height);
}
});
}
4.view.measure(int widthMeasureSpec,int heightMeasureSpec)
这个方法比较复杂,需要根据view的layoutparams来区别处理,这里放弃了。。。
demo地址:https://download.csdn.net/download/houjianbo188/10376704