码迷,mamicode.com
首页 > 移动开发 > 详细

Android在onCreate()中获得控件尺寸

时间:2014-07-21 10:26:49      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:android   style   java   color   strong   width   

@Override 
  public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      final ImageView imageView = (ImageView) findViewById(R.id.imageview);       
      int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); 
      int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); 
      imageView.measure(w, h); 
      int height =imageView.getMeasuredHeight();
      int width =imageView.getMeasuredWidth();
      textView.append("\n"+height+","+width);
      System.out.println("执行完毕.."+System.currentTimeMillis()); 
  }

//------------------------------------------------方法一 

int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); 
int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); 
imageView.measure(w, h); 
int height =imageView.getMeasuredHeight(); 
int width =imageView.getMeasuredWidth(); 
textView.append("\n"+height+","+width);

 

//-----------------------------------------------方法二 (亲测可用!在onStart()方法中调用)

ViewTreeObserver vto = imageView.getViewTreeObserver(); 
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { 
    public boolean onPreDraw() { 
        int height = imageView.getMeasuredHeight(); 
        int width = imageView.getMeasuredWidth(); 
        textView.append("\n"+height+","+width); 
        return true; 
    } 
});


//-----------------------------------------------方法三    

ViewTreeObserver vto2 = imageView.getViewTreeObserver();   
vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override   
    public void onGlobalLayout() { 
        imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);   
        textView.append("\n\n"+imageView.getHeight()+","+imageView.getWidth()); 
    }   
});


Android在onCreate()中获得控件尺寸,布布扣,bubuko.com

Android在onCreate()中获得控件尺寸

标签:android   style   java   color   strong   width   

原文地址:http://my.oschina.net/fuckboogie/blog/289750

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!