Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getmeasuredheight() and getmeasuredwidth() returns 0 after View.measure()

After measuring a View with a constant dimensions with view.measure(), the getMeasuredHeight() and getMeasureWidth() is returning 0.

layout_view.xml, layout which is inflated to create the view

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="100dp"
    android:layout_height="100dp">
</FrameLayout>

function which measures the dimensions

public void measureView(Context context){
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.layout_view,null,false);

    view.measure( View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

    Log.d(TAG,"Error width : " + view.getMeasuredWidth());
    Log.d(TAG,"Error height : " + view.getMeasuredHeight());

}
like image 541
SathMK Avatar asked Jun 26 '14 12:06

SathMK


People also ask

What is view view in android?

A view is a rectangular block on the screen used to create UI components. It refers to the android. view. View class, which is the foundation class of all views for the GUI elements.

How do you find the height of a view?

You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.


2 Answers

When you call view.getMeasuredWidth() in onCreate() or onCreateView(), the view has not been drawn yet. So you need to add a listener and will get a callback when the view is being drawn. Just like this in my code:

final ViewTreeObserver vto = view.getViewTreeObserver();
if (vto.isAlive()) {
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int viewWidth = view.getMeasuredWidth();
            // handle viewWidth here...

            if (Build.VERSION.SDK_INT < 16) {
                vto.removeGlobalOnLayoutListener(this);
            } else {
                vto.removeOnGlobalLayoutListener(this);
            }
        }
    });
}

NOTE: Remove the listener for better performance!

Don't call vto.removeOnGlobalLayoutListener(this) to remove the listener. Call it like this:

vto.getViewTreeObserver()
like image 89
Francis Shi Avatar answered Sep 24 '22 13:09

Francis Shi


Are you measuring the view in onCreate(). The view isn't drawn yet. You have to wait until a time after the view is drawn before you can measure it.

Simple solution for this is to post a runnable to the layout. The runnable will be executed after the layout has happened.

For more info See this post

Edit try to change

view.measure( View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

to

view.measure( View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY);
like image 23
Giru Bhai Avatar answered Sep 22 '22 13:09

Giru Bhai