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 heeght : " + view.getMeasuredHeight());
}
Just in case someone was experiencing this problem with ImageView:
I noticed that if your ImageView doesn't have "android:src" set (i.e. you change it dynamically) it will always return zero from getMeasuredWidth/Height.
A simple workaround would be to set a placeholder for view.
Try this way,hope this will help you to solve your problem.
if your measured view has visibility set to gone, measuring will return 0. You can set it to visible, measure, and then set back to gone, all from code.
When you call
view.getMeasuredWidth()
inonCreate()
oronCreateView()
, theview
has not been drawn yet. So you need to add a listener and will get a callback when theview
is being drawn. Just like this in my code:NOTE: Remove the listener for better performance!
Don't call
vto.removeOnGlobalLayoutListener(this)
to remove the listener. Call it like this:You can not use
View.MeasureSpec.*
directly inmeasure
call. Instead firstmakeMeasureSpec()
and then use it to invokemeasure()
: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
to