How to get the view Size and view Size
Many beginners will make a mistake, that is, to get the view Size in onCreate or onStart. However, in this way, the obtained wide Qualcomm is usually 0. Why? Because the measurement process of the view is not synchronized with the life cycle of the activity, it cannot be ensured that the view has been measured when onCreate, onStart, and onResume are executed. If the measurement is not completed, the obtained width and height will be 0.
So where can we get the view Size? There are several methods:
1. obtain it in onWindowFocusChanged.
This method is called when the focus of the Activity window is lost or the focus is obtained, such as onResume or onPause, it will be called (so it may be called multiple times ). We can use the template below to obtain the width and height of the view.
public void onWindowFocusChanged(boolean hasFocus){ super.onWindowFocusChanged(hasFocus); if(hasFocus) { int width=view.getMeasuredWidth(); int height=view.getMeasuredHeight(); }}
2. Use view. post (runnable ).
This method can deliver a runnable task to the end of the message queue. In this method, the handler of the thread where the view is located is obtained first (the thread where the view is located is the UI thread of course), and then the task is delivered to the end of the message queue corresponding to the handler, wait for the logint to get it. When the logint gets it, the view has been initialized, so you can get its width and height correctly. The code template is as follows:
protected void onStart() { super.onStart(); view.post(new Runnable(){ @Override public void run() { int width=view.getMeasuredWidth(); int height=view.getMeasuredHeight(); } }); }
3. Use ViewTreeObserver
ViewTreeObserve has many callback interfaces, such as OnGlobalLayoutListener. When the status of the view tree changes or the visibility of the view in the view tree changes, the onGlobalLayout method in this interface will be called back. You can obtain the width and height of the view at this time. Therefore, this method may be called multiple times. We should remove this interface listener after obtaining the view width and height. The code template is as follows:
@Override protected void onStart() { super.onStart(); ViewTreeObserver observer=view.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view.getViewTreeObserver().removeOnGlobalLayoutListener(this); int width=view.getMeasuredWidth(); int height=view.getMeasuredHeight(); } }); }
The preceding three methods are commonly used to obtain the view size.