`
sdkongkong
  • 浏览: 39247 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

How to get width/height of a View

 
阅读更多

Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
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.


    Using the famous OnGlobalLayoutListener:

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



    By extending a View:

    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
        }
    };



    By forcing a measurement of the View:

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

分享到:
评论

相关推荐

    gertt点阵图读取器(opengl)

    // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode ...

    opengl画图程序附带源代码

    // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails...

    Flexible Web Design Creating Liquid and Elastic Layouts with CSS.pdf

    in Chapter 1 But the alternatives to fixed width design can offer a lot of benefit and may work for more types of sites than you may think Liquid or fluid sites which resize based on the user’s ...

    android-viewflow

    GitHub has some great articles on how to get started with Git and GitHub and how to fork a project. Contributers are recommended to fork the app on GitHub (but don't have too). Create a feature ...

    flash标签云 3D效果 PHP插件 by weefselkweekje

    There are a number of things that may prevent WP-Cumulus from displaying or cause it to display a short message about how it needs the Flash plugin. * In 99% of all cases where this happens the issue...

    ViewPager 放大缩小左右移动

    * Indicates that the pager is in the process of settling to a final * position. */ public static final int SCROLL_STATE_SETTLING = 2; private int mScrollState = SCROLL_STATE_IDLE; /** * ...

    NGUI v3.5.1

    - NEW: You can now freely adjust width and height of anchored widgets. - NEW: UIDragResize script now has a maximum size limiting option as well. - FIX: Improved scroll view resizing and logic ...

    MapView的使用

    Q:how to get distance between two GeoPoints in sdk 1.0 ? MapPoint.distanceSquared(MapPoint) is gone thaks!! A:you'll need to brush up on your trigonometry, and first compute the Haversine function ...

    BIG文件编辑器

    For example, if you click inside an Object module you'll be presented with a list of Modules/Values to insert. For many values you can also use Set Value, which will present you a list of values. Just...

    matlab做软件界面

    eventdata reserved-to be defined in a future version of matlaB candles structure with handles and user data(see gUIdata) FUNCIONAMIENTO DE UNA APLICACION GUI Una aplicacion GUIDE consta de dos ...

Global site tag (gtag.js) - Google Analytics