在Android中,有时需要对控件进行测量,得到的控件宽度和高度,就必须得对手机屏幕的结构有所了解,下图所示为一个手机屏幕的大概组成部分,当然布局的格式可以自定义:
对屏幕的组成有所了解后,我们就可以根据需求获取想要设置地方的尺寸,在Android中OnCreate函数中通过控件对象调用getHeight方法获取到的仍然是0,Measure方法之后调用getMeasuredWidth的值还是0。
原因是因为当OnCreate函数发生时,只是提供了数据初始化的机会,此时还没有正式绘制图形。而绘制图形在OnDraw中进行,此时计算又显得太晚。容易想到的办法是:希望能在程序刚刚测量好某个指定控件后,拿到它的宽度和高度立刻进行计算或数据初始化。这就需要有一个方法来监听到这个事件的发生,幸好Android提供了这样的机制,利用View类中的getViewTreeObserver方法,可以获取到指定View的观察者,在绘制控件前的一刹那进行回调,这样速度上又不耽误,得到的数据由是准确的,但此方法在之后可能会被反复调用,因此需要加入限制,普通需求下,只计算一次就够了,java中获取尺寸代码如下:
获取控件尺寸代码:
方法一:
View layout = findViewById(R.id.popwindow_btn);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
if (hasMeasured == false) {
int btWidth = layout.getMeasuredWidth();
int btHeight = layout.getMeasuredHeight();
hasMeasured = true;
}
return true;
}
});
方法二:
ViewTreeObserver vto = mPopupBtn.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (hasMeasured == false) {
int btWidth = mPopupBtn.getMeasuredWidth();
int btHeight = mPopupBtn.getMeasuredHeight();
hasMeasured = true;
}
});
获取状态栏尺寸代码
<span style="color:#000000;"> /**
* 状态栏高度
*
* @return
*/
public int getStatusBarHeight() {
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
return statusBarHeight;
}
</span>
获取标题栏尺寸代码:
/**
* 获取标题栏高度
*
* @return
*/
public int getTitleBarHeight() {
int statusBarHeight = getStatusBarHeight();
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
// statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight;
return titleBarHeight;
}
public int getTitleBarHeight(){
return getActionBar().getHeight();
}
获取手机屏幕尺寸
/**
* 获取手机屏幕尺寸 width,height
*
* @return
*/
public int[] getScreenSize() {
DisplayMetrics dm = new DisplayMetrics();
// 获取屏幕信息
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeigh = dm.heightPixels;
return new int[] { screenWidth, screenHeigh };
}
获取内容区域尺寸
int contentViewHeight = findViewById(android.R.id.content).getHeight(); // 屏幕内容区域高度
以上内容为网上找集的整理的,有相同的请见谅。