Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android中view的寬高測量

android中view的寬高測量

編輯:關於Android編程

///

一般的,view測量的方法:

 

@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( +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( +height+,+width); //-----------------------------------------------方法二 ViewTreeObserver vto = imageView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { int height = imageView.getMeasuredHeight(); int width = imageView.getMeasuredWidth(); textView.append( +height+,+width); return true; } }); //-----------------------------------------------方法三 ViewTreeObserver vto2 = imageView.getViewTreeObserver(); vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this); textView.append( +imageView.getHeight()+,+imageView.getWidth()); } });

 

 

最近由於要做自定義view,需要測量view寬高,發現一個不錯的api:

View.MeasureSpec.makeMeasureSpec(int,int)

參數1是一個數值,基於該數值計算

參數2是一個mode,指測量的方式,mode如下:

它有三種模式:
①、UNSPECIFIED(未指定),父元素部隊自元素施加任何束縛,子元素可以得到任意想要的大小;
②、EXACTLY(完全),父元素決定自元素的確切大小,子元素將被限定在給定的邊界裡而忽略它本身大小;
③、AT_MOST(至多),子元素至多達到指定大小的值。

 

具體使用如下:

 

		int w = View.MeasureSpec.makeMeasureSpec(SCREEN_W,View.MeasureSpec.AT_MOST); 
		int h = View.MeasureSpec.makeMeasureSpec(SCREEN_H/2,View.MeasureSpec.AT_MOST); 
		view.measure(w, h);
		LogUtil.showlog(w: + w + ,h: + h);

 

 

  1. int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
  2. int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
  3. textView.measure(w, h);

     

     

     

     

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved