Get component size in activity
Code:
@Overridepublic void Onwindowfocuschanged (Boolean hasfocus) {//TODO auto-generated method Stubsuper.onwindowfocuschanged (Hasfocus); LOG.D ("TAG", "a-button1-->" +button1); LOG.D ("TAG", "a-width-->" +button1.getwidth ());}
Method: Rewrite the onwindowfocuschanged () method in the activity and get the view size directly inside the method
explanation: Rewrite the onmeasure () method can be known, this method is used to calculate the width and height of the view, so as long as the rewrite onmeasure () after the method, and then the method inside to get the size of the view is OK. Through testing, in one activity, the sequence of methods calls is as follows:
Its invocation order is activity.oncreate () →activity.onresume () →
→testimageview.onmeasure () →testimageview.onlayout () →ongloballayoutlistener () →
→activity.onwidnowfocuschanged () → ..... →
→textimageview.ondraw ()
Referenced from: http://www.xuebuyuan.com/1587193.html
get component size in fragment
code:
Button button1;private int width; private Handler mhandler; @Overridepublic View Oncreateview (layoutinflater Inflater, ViewGroup container,bundle savedinstancestate) {MView = inflater.inflate (R.layout.activity_one, NULL); Mhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated method Stubsuper.handlem Essage (msg); if (msg.what = =) {width = msg.arg1; LOG.I ("TAG", "button1-->" +button1); LOG.I ("TAG", "width-->" +width);}}; return MView;} @Overridepublic void Onresume () {//TODO auto-generated method Stubsuper.onresume (); Initwidget (); Viewtreeobserver vto = Button1.getviewtreeobserver (); Vto.addongloballayoutlistener (New Ongloballayoutlistener () {@Overridepublic void Ongloballayout () {width = Button1.getwidth (); Message msg = new Message (); msg.what = 200;msg.arg1 = Width;mhandler.sendmessage (msg);}});
Explanation: Because there is no fragment in theonwidnowfocuschanged() Such a method to rewrite, so we can only find another way, according to the above method call order, you will see Vto.addongloballayoutlistener () This also after onmeasure(), Ongloballayoutlistener is the inner class of viewtreeobserver, which can be monitored by viewtreeobserver when the layout of a view tree changes, and this method is also called when the interface is displayed. So the size of the view can be placed in this method
Referenced from: http://bbs.csdn.net/topics/390672372
Android-summarize activity and fragment when opening to get the size of the component