/**
* 重写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;
}
}
/**
* 为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);
}
});
}
/**
* 初始化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方法获取组件的宽度和高度
*/
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);
}
});
}
/**
* 在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);
}
}
};
微信公众号:infree6 或者直接扫码
原文:https://www.cnblogs.com/songjianzaina/p/10362574.html