Activity启动过程中获取组件宽高的五种方式
第一种:(重写Activity的onWindowFocusChanged方法)
/**
* 重写Acitivty的onWindowFocusChanged方法
*/
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
/**
* 当hasFocus为true的时候,说明Activity的Window对象已经获取焦点,进而Activity界面已经加载绘制完成
*/
if (hasFocus) {
int widht = titleText.getWidth();
int height = titleText.getHeight();
Log.i(TAG, "onWindowFocusChanged width:" + widht + " "
+ " height:" + height;
}
}
第二种:(为组件添加OnGlobalLayoutListener事件监听)
/**
* 为Activity的布局文件添加OnGlobalLayoutListener事件监听,当回调到onGlobalLayout方法的时候我们通过getMeasureHeight和getMeasuredWidth方法可以获取到组件的宽和高
*/
private void initOnLayoutListener() {
final ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView().getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Log.i(TAG, "开始执行onGlobalLayout().........");
int height = titleText.getMeasuredHeight();
int width = titleText.getMeasuredWidth();
Log.i(TAG, "height:" + height + " width:" + width);
// 移除GlobalLayoutListener监听
MainActivity.this.getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
第三种:(为组件添加OnPreDrawListener事件监听)
/**
* 初始化viewTreeObserver事件监听,重写OnPreDrawListener获取组件高度
*/
private void initOnPreDrawListener() {
final ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView().getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
Log.i(TAG, "开始执行onPreDraw().........");
int height = titleText.getMeasuredHeight();
int width = titleText.getMeasuredWidth();
Log.i(TAG, "height:" + height + " width:" + width);
// 移除OnPreDrawListener事件监听
MainActivity.this.getWindow().getDecorView().getViewTreeObserver().removeOnPreDrawListener(this);
return true;
}
});
}
第四种:(使用View.post方法获取组件的宽高)
/**
* 使用View的post方法获取组件的宽度和高度
*/
private void initViewHandler() {
titleText.post(new Runnable() {
@Override
public void run() {
int width = titleText.getWidth();
int height = titleText.getHeight();
Log.i(TAG, "initViewHandler height:" + height + " width:" + width);
}
});
}
第五种:(通过Handler对象使用异步消息获取组件的宽高)
/**
* 在onCreate方法中发送异步消息,在handleMessage中获取组件的宽高
*/
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 101) {
int width = titleText.getWidth();
int height = titleText.getHeight();
Log.i(TAG, "initViewHandler height:" + height + " width:" + width);
}
}
};
总结:
- 第一种重写onWidnowFocusChanged方法获取组件宽高的方式,方法可能会执行多次,这点需要我们注意
- 本人在实际开发中使用第二种较多
关于我
微信公众号:infree6 或者直接扫码