在onCreate()中获取View宽高
两种方法:
1.使用View.post(Runable runable)方法
imageView.post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: width = " + imageView.getWidth());
Log.d(TAG, "run: measuredWidth = " + imageView.getMeasuredWidth());
}
});
2.使用ViewTreeObserver:
ViewTreeObserver observer = imageView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Log.d(TAG, "onGlobalLayout: width = " + imageView.getWidth());
Log.d(TAG, "onGlobalLayout: measuredWidth = " + imageView.getMeasuredWidth());
}
});
3.可以覆写onWindowFocusChanged方法
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d(TAG, "onWindowFocusChanged: width = " + imageView.getWidth());
Log.d(TAG, "onWindowFocusChanged: measuredWidth = " + imageView.getMeasuredWidth());
}
==注意==:ViewTreeObserver和onWindowFocusChanged会被调用多次
网友评论