1.Activity# onWindowFousChanged
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
int height = main_viewpager.getMeasuredHeight();
int width = main_viewpager.getMeasuredWidth();
}
}
多次调用在窗口得到焦点和失去焦点
2.view.post(runnable)
@Override
protected void onStart() {
super.onStart();
main_viewpager.post(new Runnable() {
@Override
public void run() {
int height = main_viewpager.getMeasuredHeight();
int width = main_viewpager.getMeasuredWidth();
}
});
}
3.ViewTreeObserver
@Override
protected void onStart() {
super.onStart();
ViewTreeObserver viewTreeObserver = main_viewpager.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
main_viewpager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int height = main_viewpager.getMeasuredHeight();
int width = main_viewpager.getMeasuredWidth();
}
});
}
View 树的状态改变,onGlobalLayout 会被调用多次
本文介绍了Android中四种获取视图尺寸的方法:Activity#onWindowFocusChanged、view.post(runnable)、ViewTreeObserver及view.measure。这些方法适用于不同场景,如响应窗口焦点变化、延迟执行任务、监听全局布局变化及手动测量视图尺寸。
1589

被折叠的 条评论
为什么被折叠?



