Most Android developers will encounter the OnCreate method to get the width of the component to do some processing, but unfortunately all the results are 0, this is due to the Android rendering mode is determined, when the component is created but not displayed when the fixed width of the component can not be obtained, Here are some ways to get the width of a component in the OnCreate method:
Method One:
/** * Measurement method gets the dimension size of the component * * /int width = View.MeasureSpec.makeMeasureSpec (0 , View.MeasureSpec.UNSPECIFIED); int height = View.MeasureSpec.makeMeasureSpec (0, View.MeasureSpec.UNSPECIFIED); Button.measure (width,height); int buttonheight = button.getmeasuredheight (); int buttonwidth = button.getmeasuredwidth (); LOG.E (Tag,"Calculate method Get component Size Button.width =" + Buttonwidth + " button.height =" + buttonheight);
Method Two:
/*** Increased overall layout monitoring **/Viewtreeobserver Vto2=Button.getviewtreeobserver (); Vto2.addongloballayoutlistener (NewViewtreeobserver.ongloballayoutlistener () {@Override Public voidongloballayout () {button.getviewtreeobserver (). Removeglobalonlayoutlistener ( This); intHeight =button.getmeasuredheight (); intwidth =button.getmeasuredwidth (); LOG.E (Tag,"Overall layout listener get component Size Button.width =" + width + "Button.height =" +height); TextView TV=NewTextView (mainactivity. This); Tv.settext ("Hello world!"); Tv.settextcolor (color.red); Tv.setlayoutparams (Newlayoutparams (layoutparams.wrap_content, layoutparams.wrap_content)); Layout.addview (TV); } });
Method Three:
/*** Add component Draw Listener method (this method is sometimes invalid, the specific reason is unknown) **/viewtreeobserver vto=Button.getviewtreeobserver (); Vto.addonpredrawlistener (NewViewtreeobserver.onpredrawlistener () {@Override Public BooleanOnpredraw () {//TODO auto-generated Method Stub intHeight =button.getmeasuredheight (); intwidth =button.getmeasuredwidth (); LOG.E (Tag,"Component Draw listener get component size Button.width =" + width + "Button.height =" +height); return true; } });
In fact, there is a very good method, independent of what we know about the Android life cycle, after the Onresume method, the activity will also call the public void Onwindowfocuschanged (Boolean Hasfocus) This method, You will magically find that in this method all the components you want are not available to you, but the method is called every time the window focus changes, and you can use this method with unexpected results.
Android Gets the component size in OnCreate