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());
}
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.
You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.
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()
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With