OnMeasure错误的高度(需要可用空间的高度)

时间:2016-01-12 12:58:48

标签: android

enter image description here

我正在尝试根据可用空间的高度和宽度缩放自定义视图。所以它应该填充绿色箭头和宽度的高度空间。但我从heightMeasureSpec = View.MeasureSpec.getSize(heightMeasureSpec); 回来的像素 是1080,这是我显示器的大小。

如何获得可用空间的高度,以及ID为“test”

的布局

布局:

  <RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#FFCCCCCC"
    android:orientation="vertical"
    tools:context=".MainActivity" >
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:scaleType="centerCrop"
    android:contentDescription="@string/background"
    android:src="@drawable/background" />
    <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical">
    <include
    android:id="@+id/tool_bar"
    layout="@layout/tool_bar" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <LinearLayout
            android:id="@+id/test"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <nl.bla.test.customview
                android:id="@+id/test2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="#FFFFFFFF" />
        </LinearLayout>
    </LinearLayout>
   </LinearLayout>
   </RelativeLayout>

自定义视图的onMeasure方法:

   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    widthMeasureSpec = View.MeasureSpec.getSize(widthMeasureSpec);
    heightMeasureSpec = View.MeasureSpec.getSize(heightMeasureSpec);


    float f = Math.min(widthMeasureSpec / 1280.0F, heightMeasureSpec / 720.0F);
    Log.i("float f = ", "" + widthMeasureSpec + " " + heightMeasureSpec) ;
    setMeasuredDimension(1280, 720);
    setPivotX(0.0F);
    setPivotY(0.0F);
    setScaleX(f);
    setScaleY(f);

}

1 个答案:

答案 0 :(得分:1)

想通了, 这给了我正确的高度和宽度:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
float f = (float) Math.min(width / 1280.0, height / 720.0);
Log.i("OnMeasureTest",""+height);
setMeasuredDimension(1280, 720);
setPivotX(0.0F);
setPivotY(0.0F);
setScaleX(f);
setScaleY(f);

}