Many people in the activity main thread call GetWidth, getmeasuredwidth, but get not the width of the view, this is because the view is not finished drawing, of course, what to do?
Method One, measure yourself:
int w = View.MeasureSpec.makeMeasureSpec (0,view.measurespec.unspecified); int h = View.MeasureSpec.makeMeasureSpec (0, View.MeasureSpec.UNSPECIFIED); View.measure (W, h); int height = view.getmeasuredheight (); int width = Vew.getmeasuredwidth ();
Method Two, add the drawing listener and get the size of the view after the drawing finishes:
View.getviewtreeobserver (). Addonpredrawlistener (New viewtreeobserver.onpredrawlistener () { public boolean onpredraw () { View.getviewtreeobserver (). Removeonpredrawlistener (This); int height = view.getmeasuredheight (); int width = view.getmeasuredwidth (); return true; } });
方法三,添加全局布局变化监听:
View.getviewtreeobserver (). Addongloballayoutlistener (New Ongloballayoutlistener () {@Override Pub LIC void Ongloballayout () {view.getviewtreeobserver (). Removeglobalonlayoutlistener (this); View.getheight (); View.getwidth (); } });
How to get to the height of the Android control