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();

58 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