How to get width/height of a View

As the idea of the Android evolved, Android has received wide attention and deployed on a very wide range of devices. Android UI had to move and make developers' life easier: AbsoluteLayout got deprecated. It is very logical because your app will be installed on very small devices and very large devices and all the devices in between.

Now, it is all WRAP_CONTENT, FILL_PARENT/MATCH_PARENT. Yet, a developer sometimes needs to know the dimensions of his view to do some extra tweaks to perfect his ui.

So, what is the best way to do so?
Well, there are several ways of getting the dimensions of a view. Most of them boil down to waiting the layout of the view hierarchy. In case you still have not gotten into the problem of getWidth() and getHeight() returning 0, well that is very normal in Android as the width and height of a view are zero until they are visible, measured, and part of the layout.

In the following I will assume that your View is called view.


  1. Using the famous OnGlobalLayoutListener:

  2. This is one of the most used mechanisms to get the view dimensions. You attach a Global Layout Listener to the view hierarchy. It helps you actually get the width of all the views in your view heirarchy:

    view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
     @SuppressLint("NewApi")
     @SuppressWarnings("deprecation")
     @Override
      public void onGlobalLayout() {
       //now we can retrieve the width and height
       int width = view.getWidth();
       int height = view.getHeight();
       //...
       //do whatever you want with them
       //...
       //this is an important step not to keep receiving callbacks:
       //we should remove this listener
       //I use the function to remove it based on the api level!
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) view.getViewTreeObserver().removeOnGlobalLayoutListener(this); else view.getViewTreeObserver().removeGlobalOnLayoutListener(this); } });


  3. By extending a View:

  4. Personally, I use this approach when the whole Activity or Layout is really dependant on one view only, most probably, a GridView or a ListView. I have already presented this solution on one SO question: How to manage GridView. The whole idea is to instantiate your view in your code instead of inserting it in the layout xml, and by doing this, you are able to override the onLayout function.

    mGrid = new GridView(this) {
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            //here you have the size of the view and you can do stuff
        }
    };


  5. By forcing a measurement of the View:

  6. This way is probably rarely used but I personally like it. I am not 100% sure but this probably is the most lightweight of them all, although it might not be as precise. If you force the view to measure itself, you can get the measured dimensions. I use this when you need to move some views (using their margins) based on other views when you can not simply use some of the layout properties because they have different parents or something. Here is the way to do it:

    view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    int widht = view.getMeasuredWidth();
    int height = view.getMeasuredHeight();

95 comments:

  1. Thank you very much. It's not so easy understand this concept without an explication.

    ReplyDelete
    Replies

    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

      Delete
  2. The third solution is perfect for my current case.
    (I use pixels between 0 and 100 in the xml to simulate percentages of screen size, and then compute at runtime the positions of the centres of my child views, relative to the screen size.)
    Thank you sir.
    O.C.

    ReplyDelete
  3. Thank you very much brother. I've been trying to figure this out all day and it's helped me a TON!

    ReplyDelete
  4. THANKS A LOT!!!
    Very very helpful! You saved me bro! :)

    ReplyDelete
  5. The technic N°3 don't work if the view has a "layout_weight", it's returning the minimum size of it, not the stretched one.

    ReplyDelete
  6. Thx a lot!!!!!
    Very useful!!!!!

    ReplyDelete
  7. dude, thank you so damn much!

    ReplyDelete
  8. In my case, I had to hide a view if it is getting shirked. I tried too many ways and all were failing at some cases.

    Finally tried your 3rd solution and I made it. Thank you for such good article.

    ReplyDelete

  9. This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of informative things...
    iOS Training in Chennai
    Android Training in Chennai
    php Training in Chennai

    ReplyDelete
    Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

      Delete
  10. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    Mobile App Development Company in Chennai
    Android app Development Company in Chennai
    ios app development Company in Chennai

    ReplyDelete
  11. Thanks a lot, very Useful, solution #3 worked for me :)

    ReplyDelete

  12. Nice it seems to be good post... It will get readers engagement on the article since readers engagement plays an vital role in every blog.. i am expecting more updated posts from your hands.
    Android App Development Company

    ReplyDelete
  13. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    Mobile App Development Company

    ReplyDelete
  14. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
  15. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text

    ReplyDelete
  16. Good one, you post much informative blog, hope i forward to my friends as well.. thanks for sharing your valuable ideas and views...keep rocks...
    Android Training with placement in chennai | Android Training in velachery |Android Training

    ReplyDelete
  17. Thank you for taking the time to provide us with your valuable information.
    Freshers Jobs in Chennai

    ReplyDelete
  18. great and nice blog thanks sharing..I just want to say that all the information you have given here is awesome...Thank you very much for this one.
    web design Company
    web development Company
    web design Company in chennai
    web development Company in chennai
    web design Company in India
    web development Company in India

    ReplyDelete
  19. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    Texting API
    Text message marketing
    Digital Mobile Marketing
    Sms API
    Sms marketing

    ReplyDelete
  20. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Mobile Marketing Service
    Mobile Marketing Companies

    ReplyDelete
  21. Good post and I like it very much. By the way, anybody try this increase app downloads? I do not how to use.

    ReplyDelete
  22. Very interesting,good job and thanks for sharing such a good blog.your article is so convincing that I never stop myself to say something about it.You’re doing a great job.Keep it up

    PSD to Wordpress
    wordpress website development

    ReplyDelete
  23. This is excellent information. Your blog is like professional! Do you want to find best premium wordpress templates for any kind of business? go here https://wordpresstemplates.ch/

    ReplyDelete
  24. This comment has been removed by the author.

    ReplyDelete
  25. I was more than happy to uncover this great site. I need to to thank you for your time due to this fantastic read!! http://infocampus.co.in/advanced-java-training-bangalore.html

    ReplyDelete
  26. android app marketing Thank you for your article.Much thanks again. Want more.

    ReplyDelete
  27. Thanks for sharing, nice post! Post really provice useful information!

    Giaonhan247 chuyên dịch vụ uy tín, giá rẻ với cước phí vận chuyển hàng đi mỹ từ dịch vụ chuyển hàng đi mỹ giá rẻ nhất với dịch vụ dich vu ship hang my cũng như giải đáp mua đồng hồ trên ebay có đảm bảo không hay có nên mua đồng hồ trên ebay không và là công ty vận chuyển hàng đi lào uy tín nhất.

    ReplyDelete
  28. Thanks for sharing this post (Y)

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. good information for self study

    ReplyDelete


  31. Just seen your Article, it amazed me and surpised me with god thoughts that eveyone will benefit from it. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
    Thanks
    DedicatedHosting4u.com


    ReplyDelete
  32. Soma pill is very effective as a painkiller that helps us to get effective relief from pain. This cannot cure pain. Yet when it is taken with proper rest, it can offer you effective relief from pain.
    This painkiller can offer you relief from any kind of pain. But Soma 350 mg is best in treating acute pain. Acute pain is a type of short-term pain which is sharp in nature. Buy Soma 350 mg online to get relief from your acute pain.

    https://globalonlinepills.com/product/soma-350-mg/


    Buy Soma 350 mg
    Soma Pill
    Buy Soma 350 mg online



    Buy Soma 350 mg online
    Soma Pill
    Buy Soma 350 mg

    ReplyDelete
  33. With Sanjay Baghela, your business Website is in safe hands. He and his team are the best SEO Expert in India the leading digital marketing field. They work with the most trusted & advanced SEO strategies and tools to deliver the results, which you are expecting from the team. The Freelance Seo Expert In India of Sanjay Badhela is serving their SEO solutions and best known as the best SEO Consultant across the globe. You can Hire Seo consultant anytime from the team of best Freelance Seo Expert and can discuss the things to get better for your online business promotion.
    Best SEO Expert In India and BEST SEO Company in India

    ReplyDelete
  34. You've made some really good points there. I checked on the web for more info about the issue and found most individuals will go along with your views on this web site.
    rice purity test link

    ReplyDelete
  35. thank you for sharing this awesome information. and visit our blog site alsoSatta King
    of course you already have a type of expertise that will not erode. Because it is true that this activity
    Digital Marketing Agency UK
    https://daora2.com/
    https://mbc1588.cafe24.com
    https://powerball888.com/powerball/
    https://bet365kor1.com/
    http://makeland.link/higaming/
    https://ocn2001.com/

    ReplyDelete
  36. I also wanted to say my "biggest thank you" to everyone who participated and has been involved into creating of this project.

    ReplyDelete
  37. Good day! I simply would like to give you a huge thumbs up for your great information you have here on this post. I am returning to your website for more soon.
    Tech PC

    ReplyDelete
  38. live draw hk banyak terdapat perbedaan dari situs2 penyedia live hk ini. Sedikit saran apabila anda setiap harinya mengikuti live draw hk kami pastikan selalu menggunakan situs live hk yang kami rekomendasikan saja. Termasuk juga untuk live draw sgp ataupun live sgp alternatif ini.

    ReplyDelete
  39. Great efforts put to find the list of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create relations. You’re doing great work. Keep it up.

    Magento Development Training Course in Chennai Zuan Education

    Selenium Training Course in Chennai Zuan Education

    ReplyDelete
  40. Poker online situs terbaik yang kini dapat dimainkan seperti Bandar Poker yang menyediakan beberapa situs lainnya seperti http://62.171.128.49/hondaqq/ , kemudian http://62.171.128.49/gesitqq/, http://62.171.128.49/gelangqq/, dan http://62.171.128.49/seniqq. yang paling akhir yaitu http://62.171.128.49/pokerwalet/. Jangan lupa mendaftar di panenqq

    ReplyDelete
  41. Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.
    Digital Marketing Course In Kolkata

    ReplyDelete
  42. I have much more information from this great blog. I am glad to read your article and Thank you...!

    7 tips to start a career in digital marketing

    “Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”.

    we have offered to the advanced syllabus course digital marketing for available join now

    more details click the link now

    https://www.webdschool.com/digital-marketing-course-in-chennai.html

    ReplyDelete
  43. The blog you shared is very good. I expect more information from you like this blog. Thank you.

    Web designing trends in 2020

    When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, Whats App, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

    we have offered to the advanced syllabus course web design and development for available join now

    more details click the link now

    https://www.webdschool.com/web-development-course-in-chennai.html

    ReplyDelete
  44. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
    Digital Marketing Course In Kolkata
    Web Design Course In Kolkata

    ReplyDelete
  45. Nice blog, it’s so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
    Digital Marketing Course In Kolkata
    Web Design Course In Kolkata

    ReplyDelete
  46. I really love your site.. Great colors & theme. Did you develop this web site yourself? develop Please reply back as I’m planning to create my very own blog and would love to learn where you got this from or exactly what the theme is called. Thank you!

    ReplyDelete
  47. I really like looking through a post tv that can make people think. Also, thank you for permitting me to comment!

    ReplyDelete
  48. After looking over a few of the articles on your site, I really like your technique of writing a blog. I book marked it to my bookmark web page list and will be checking back soon. education Please check out my website too and tell me your opinion.

    ReplyDelete
  49. The next time I examine a weblog, I wish that it does now not fail me genuinely as a good deal as this specific one. I imply, I comprehend it was my choice to observe, despite the fact that I definitely believed you will likely have some aspect beneficial to speak about. click All I listen is a gaggle of whining about some thing you may restore if you have been now not too busy seeking out attention.

    ReplyDelete

  50. Top chauffeur Cab service in Victoria
    Best Chauffeur cab service in Melbourne
    Silver Executive Cab is a Chauffeur Cars company in Melbourne specifically company targets Melbourne Airport transfers, Corporate transfers, Regular Pick-ups, Wedding Hire Cars & private hire cars. It is an essay way to contact at Silver Executive Cab & you will get proper feedback or support by our technical executives.

    ReplyDelete
  51. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    workday studio online training
    best workday studio online training
    top workday studio online training

    ReplyDelete
  52. Thanks for sharing this nice informations.
    artificial intelligence training in coimbatore

    Blue prism training in coimbatore

    RPA Course in coimbatore

    C and C++ training in coimbatore

    big data training in coimbatore

    hadoop training in coimbatore

    aws training in coimbatore

    ReplyDelete
  53. AndroidiOSZone is a leading Mobile apps development company in Noida. where our dedicated team members provide world-class technology solutions to game the competitive market. Share your app idea and Contact Us At 91-9899130284.

    ReplyDelete