Android 获得View的宽和高

在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 booleanonPreDraw() {
        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(); 
    
});
那么,在activity进入运行期时,组件的尺寸获取方法就很简单了,直接getWidth()和getHeight().






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 booleanonPreDraw() {
        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(); 
    
});
那么,在activity进入运行期时,组件的尺寸获取方法就很简单了,直接getWidth()和getHeight().

你可能感兴趣的:(android,view,宽和高)