To get the height and width of the phone screen in Android, we know that the value obtained in the OnCreate method is 0 , and some people say that you can get the value in the OnClick method, which is also a method But in the Onwindowfocuschanged method can be directly obtained, and sometimes the needs of the scene, you have to get the value immediately after the activity rendering is complete, this time the Onwindowfocuschanged () method is used to implement, Similar to the Popupwindow display, if executed in the OnCreate method, the exception is reported without token, because the activity is not rendered successfully.
Onwindowfocuschanged (): This method is called when the activity's current window Gets or loses focus. When this method is recalled, the activity is completely visible to the user (only visible, still black, pending draw). This method is called when the dialog box bounces/disappears and the activity is newly created and rolled back.
By contrast, the Onresume () method is more about the activity entering the visible state, but only the state, not the actual interface build is complete.
Demo
An activity shows only one testimageview, and overrides the Onmeasure (), OnLayout (), OnDraw () methods under Testimageview, and sets Ongloballayout () to listen for them, Observe the sequence of calls of these methods with activity Onresume (), onwindowfocuschanged (), as follows:
Clipdrawableactivity onCreate () time=1376920332125clipdrawableactivity onresume () testimageview.width=0 time=1376920332149mainactivity onwindowfocuschanged Hasfocus=falseclipdrawableactivity Testimageview onmeasure () clipdrawableactivity Testimageview onMeasure () Clipdrawableactivity Testimageview onmeasure () clipdrawableactivity testimageview onMeasure () ClipDrawableActivity Testimageview onlayout () clipdrawableactivity ongloballayout () testimageview.width=736 time=1376920332185clipdrawableactivity onwindowfocuschanged () Hasfocus=truetestimageview.width=736 time=1376920332187clipdrawableactivity Testimageview onmeasure () clipdrawableactivity Testimageview onMeasure () Clipdrawableactivity Testimageview onlayout () clipdrawableactivity ongloballayout () TestImageView.width=736 time=1376920332194clipdrawableactivity Testimageview OnDraw ()
Activity.oncreate () →activity.onresume () →testimageview.onmeasure () →testimageview.onlayout () →ongloballayoutlistener () →activity.onwidnowfocuschanged () → ..... →textimageview.ondraw ()
Summary
At this point, if you need to get the width of a view, you can get it directly at Onwindowfocuschanged (), which is more convenient than the way a view is set Ongloballayoutlistener. For example, for the need to read local file records to determine whether it is the first time to open the interface to prompt the text picture, you can also read in this method and then display on the UI.
I'm the dividing line of the king of the land Tiger.
Android--Onwindowfocuschanged