///
一般的,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.addOnGlobalLayoutListene
r(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
imageView.getViewTreeObserver().removeGlobalOnLayoutList
ener(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);
- int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
- int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
- textView.measure(w, h);