在oncreate()方法中獲取控件的寬高,只會獲得0,緣由是oncreate()方法執行完成後控件纔會被度量(measure),因此咱們在onCreate方法裏面經過view.getHeight()獲取控件的高度或者寬度確定是0,由於它本身尚未被度量,也就是說他本身都不知道本身有多高,而你這時候去獲取它的尺寸,確定是不行的. 解決方法:java
//------------------------------------------------方法一app
<!-- lang: java -->ide
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);
//-----------------------------------------------方法二this
<!-- lang: java -->code
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; } });
//-----------------------------------------------方法三server
<!-- lang: java -->rem
ViewTreeObserver vto2 = imageView.getViewTreeObserver(); vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this); textView.append("\n\n"+imageView.getHeight()+","+imageView.getWidth()); } });
方法一: 比其餘的兩個方法多了一次計算,也就是多調用了一次onMeasure()方法,該方法雖然看上去簡單,可是若是要目標控件計算耗時比較大的話(如listView等),不建議使用. 方法二,在繪製前執行回調方法,它的回調方法會調用不少次,而且滑動TextView的時候任然會調用,因此不建議使用. 方法三,當layout或控件的visibility被調用時,執行此回調get
方法四:it
<!-- lang: java --> private void measureItem(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec, mListPadding.left + mListPadding.right, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); }