获取View宽高的四种方式
2021-01-27 本文已影响0人
合拍v
一开始写Android获取view的宽高的时候,经常会直接调用一些方法,实际获得的宽高都是0。后来才知道是因为View宽高的测量与Activity的生命周期并不是同步的,调用函数的时候很可能View的measure函数还没有执行完,下面介绍四种获取View宽高的方式。
- onWindowFocusChanged
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
}
- view.post(runnable)
@Override
protected void onStart() {
super.onStart();
view.post(new Runnable() {
@Override
public void run() {
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
- ViewTreeObserver
@Override
protected void onStart() {
super.onStart();
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
@SuppressWarnings(value = "deprecation")
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
-
view.measure(int widthMeasureSpec, int heightMeasureSpec)
这种方法手动测量View的宽高,需要分三种情况:
(1) View宽高为具体的值w, h
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);
(2) 设置为wrap_content
int widthMeasureSpec =
View.MeasureSpec.makeMeasureSpec(((1 << 30) - 1), View.MeasureSpec.AT_MOST);
int heightMeasureSpec =
View.MeasureSpec.makeMeasureSpec(((1 << 30) - 1), View.MeasureSpec.AT_MOST);
view.measure(widthMeasureSpec, heightMeasureSpec);
(3)设置为match_parent时是不能测出具体的宽高的,因为获取不到parentSize。