android--get the view's wide height

Source: Internet
Author: User

    1. It is not feasible to call the View.getwidth () and View.getheight () methods in the Activity lifecycle Method: OnCreate (), OnStart (), Onresume () to get the height of the view Because the layout is not loaded at this time, it is not visible.

      Also, when the visible state of the view is: GONE, the width of the obtained height is also 0;

2. Workaround:

(1) Direct measurement:

private void First () {int width = View.MeasureSpec.makeMeasureSpec (0,view.measurespec.unspecified); int height = View.MeasureSpec.makeMeasureSpec (0,view.measurespec.unspecified); textview.measure (width, height); int height1 = Textview.getmeasuredheight (); int width2 = Textview.getmeasuredwidth (); System.out.println ("First: Width:" + width2 + "High:" + height1);}

(2) Adding a listener before drawing the view

private void Second () {Viewtreeobserver vto = Textview.getviewtreeobserver (); Vto.addonpredrawlistener ( Newviewtreeobserver.onpredrawlistener () {public Boolean onpredraw () {int height = textview.getmeasuredheight (); int width = Textview.getmeasuredwidth (); System.out.println ("Second: Width:" + width + "Height:" + height); return true;});

(3) Add overall layout monitoring

private void Third () {Viewtreeobserver vto = Textview.getviewtreeobserver (); Vto.addongloballayoutlistener (new Ongloballayoutlistener () {public void Ongloballayout () {textview.getviewtreeobserver (). Removeglobalonlayoutlistener (this); int height = textview.getmeasuredheight (); int width = Textview.getmeasuredwidth () ; System.out.println ("Third: Width:" + width + "Height:" + height);});}


This article is from the "Androidcamera Summary" blog, please be sure to keep this source http://7183397.blog.51cto.com/7173397/1606535

android--get the view's wide height

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.