gpt4 book ai didi

android - OnMeasure 得到错误的高度(需要可用空间的高度)

转载 作者:行者123 更新时间:2023-11-30 01:39:04 56 4
gpt4 key购买 nike

enter image description here

我正在尝试根据可用空间的高度和宽度来缩放自定义 View 。所以它应该填充绿色箭头高度和宽度的空间。但是我从 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>

自定义 View 的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);

}

最佳答案

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

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);

关于android - OnMeasure 得到错误的高度(需要可用空间的高度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34744358/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com