bazysong
bazysong

Reputation: 379

Android getMeasuredHeight get wrong value

I have the XML like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000" >
<com.XXXXXXXXXXX.view
    android:layout_width="200dp"
    android:background="#ffffff"
    android:layout_height="400dp"
    android:layout_centerInParent="true" />

I get the view height in the method onMesure like this:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (!isMeasured)
    {
        isMeasured = true;
        mViewHeight = getMeasuredHeight();
        mViewWidth = getMeasuredWidth();...}

the mViewWidth is right(600px), but the mViewHeight is wrong(1626px).
Could someone give me some pointers?
Tks a lot.

Upvotes: 3

Views: 4110

Answers (1)

Jim
Jim

Reputation: 833

getMeasuredHeight() will return the desired height for the child, not necessarily the height it actually gets. You also are taking the first measured value and setting your width/height to that. onMeasure can be called multiple times for different reasons. The intent is to say how much height/width your view desires with the given MeasureSpec constraints. onLayout will get called later with where your parent actually wants you, which may not match what you asked for in onMeasure.

Also, views already have a getWidth() and getHeight() which are valid after the layout pass. Do you need your own mViewWidth and mViewHeight?

Upvotes: 3

Related Questions