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

28 comments:

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

    ReplyDelete
  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