Measure the width and height of a view in android
///
Generally, the view measurement method is as follows:
@ 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 (Execution completed... + System. currentTimeMillis ()); } // -------------------------------------------------- Method 1 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 ); // ------------------------------------------------- Method 2 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; } }); // ------------------------------------------------- Method 3 ViewTreeObserver vto2 = imageView. getViewTreeObserver (); Vto2.addOnGlobalLayoutListene R (new OnGlobalLayoutListener (){ @ Override Public void onGlobalLayout (){ ImageView. getViewTreeObserver (). removeGlobalOnLayoutList Ener (this ); TextView. append (+ imageView. getHeight () +, + imageView. getWidth ()); } });
Recently, to customize the view, you need to measure the view width and height and find a good api:
View. MeasureSpec. makeMeasureSpec (int, int)
Parameter 1 is a value calculated based on this value
Parameter 2 is a mode, which refers to the measurement method. The mode is as follows:
It has three modes:
① UNSPECIFIED (not specified). The parent element forces any constraint on the element, and the child element can get any desired size;
② EXACTLY (complete). The parent element determines the exact size of the Self-element. The child element is limited to the given boundary and its size is ignored;
③ AT_MOST (at most). The child element can reach the specified size at most.
The specific usage is as follows:
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 );