在oncreate()中利用view.getWidth()或是view.getHeiht()来获取view的宽和高,看似没有问题,其实他们去得值是0,并不是你想要的结果?
这是为什么呢?
在调用oncreate()方法时,界面处于不可见状态,内存加载组件还没有绘制出来,你是无法获取他的尺寸。
那如何在绘制组件之前能获取到该组件的尺寸大小呢?
这里有三种方法,经过验证的:
方法一 ://测量方法
1
2
3
4
5
|
int
width =View.MeasureSpec.makeMeasureSpec(
0
,View.MeasureSpec.UNSPECIFIED);
int
height =View.MeasureSpec.makeMeasureSpec(
0
,View.MeasureSpec.UNSPECIFIED);
view.measure(width,height);
int
height=view.getMeasuredHeight();
int
width=view.getMeasuredWidth();
|
方法二 :
1
2
3
4
5
6
7
8
9
|
//增加组件绘制之前的监听
ViewTreeObserver vto =view.getViewTreeObserver();
vto.addOnPreDrawListener(
new
ViewTreeObserver.OnPreDrawListener() {
@Override
public
boolean onPreDraw() {
int
height =view.getMeasuredHeight();
int
width =view.getMeasuredWidth();
}
});
|
1
2
3
4
5
6
7
8
9
10
|
//增加整体布局监听
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(
new
OnGlobalLayoutListener(){
@Override
public
voidonGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(
this
);
int
height =view.getMeasuredHeight();
int
width =view.getMeasuredWidth();
}
});
|
这个方法有点复杂,activitiy的生命周期中有个函数onWindowFocusChanged(),这个函数是在所有View被绘制完成后立马调用,在这个方法里调用view.getWidth()和view.getHeiht()就可以得到View的宽度和高度。
在onCreate方法中我们通过mView.getWidth()和mView.getHeight()获取到的view的宽高都是0,那么下面几种方法就可以在onCreate方法中获取到view的宽高。
1、
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); mTextView.measure(w, h); int height = mTextView.getMeasuredHeight(); int width = mTextView.getMeasuredWidth(); System.out.println("measure width=" + width + " height=" + height);
2、mViewTreeObserver = mTextView.getViewTreeObserver();
mViewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // TODO Auto-generated method stub mTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this); System.out.println("onGlobalLayout width=" + mTextView.getWidth() + " height=" + mTextView.getHeight()); } });
3、
mViewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() { @Override public boolean onPreDraw() { // TODO Auto-generated method stub mTextView.getViewTreeObserver().removeOnPreDrawListener(this); System.out.println("onPreDraw width=" + mTextView.getWidth() + " height=" + mTextView.getHeight()); return true; } });
4、
@Override public void onWindowFocusChanged(boolean hasFocus) { // TODO Auto-generated method stub super.onWindowFocusChanged(hasFocus); if (hasFocus) { System.out.println("onWindowFocusChanged width=" + mTextView.getWidth() + " height=" + mTextView.getHeight()); } }
打印结果: