如何根据父视图的尺寸调整Android视图的大小

如何根据其父布局的大小调整视图的大小。例如,我有一个RelativeLayout可以填满整个屏幕的,并且我想要一个子视图(例如)ImageView占据整个高度,而宽度占整个宽度的1/2?

我试图重写所有的onMeasureonLayoutonSizeChanged,等我无法得到它的工作....


森林海
浏览 787回答 3
3回答

慕容3067478

我不知道是否有人还在读这个线程,但是Jeff的解决方案只会使您半途而废(按字面意思)。他的onMeasure所要做的就是在一半的父对象中显示一半的图像。问题在于,在之前调用super.onMeasure setMeasuredDimension会根据原始大小测量视图中的所有子项,然后在setMeasuredDimension调整视图大小时将其切成两半。相反,您需要调用setMeasuredDimension(根据onMeasure覆盖要求)并为LayoutParams视图提供一个新值,然后调用super.onMeasure。请记住,您LayoutParams是从视图的父类型派生的,而不是视图的类型。@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){   int parentWidth = MeasureSpec.getSize(widthMeasureSpec);   int parentHeight = MeasureSpec.getSize(heightMeasureSpec);   this.setMeasuredDimension(parentWidth/2, parentHeight);   this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));   super.onMeasure(widthMeasureSpec, heightMeasureSpec);}我相信您唯一一次与父母有麻烦的地方就是父母LayoutParam

守候你守候我

您可以通过创建自定义View并覆盖onMeasure()方法来解决此问题。如果您始终在xml中的layout_width中使用“ fill_parent”,则传递给onMeasusre()方法的widthMeasureSpec参数应包含父级的宽度。public class MyCustomView extends TextView {&nbsp; &nbsp; public MyCustomView(Context context, AttributeSet attrs) {&nbsp; &nbsp; &nbsp; &nbsp; super(context, attrs);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {&nbsp; &nbsp; &nbsp; &nbsp; super.onMeasure(widthMeasureSpec, heightMeasureSpec);&nbsp; &nbsp; &nbsp; &nbsp; int parentWidth = MeasureSpec.getSize(widthMeasureSpec);&nbsp; &nbsp; &nbsp; &nbsp; int parentHeight = MeasureSpec.getSize(heightMeasureSpec);&nbsp; &nbsp; &nbsp; &nbsp; this.setMeasuredDimension(parentWidth / 2, parentHeight);&nbsp; &nbsp; }}&nbsp; &nbsp;您的XML看起来像这样:<LinearLayout&nbsp;&nbsp; &nbsp; android:layout_width="match_parent"&nbsp; &nbsp; android:layout_height="match_parent">&nbsp; &nbsp; <view&nbsp; &nbsp; &nbsp; &nbsp; class="com.company.MyCustomView"&nbsp; &nbsp; &nbsp; &nbsp; android:layout_width="match_parent"&nbsp; &nbsp; &nbsp; &nbsp; android:layout_height="match_parent" /></LinearLayout>

隔江千里

我发现最好不要自己设置测量尺寸。父视图和子视图之间实际上需要进行一些协商,并且您不想重写所有这些代码。但是,您可以做的是修改measureSpecs,然后使用它们调用super。您的视图将永远不会知道它正在从其父级收到经过修改的消息,并将为您处理所有事情:@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {&nbsp; &nbsp; int parentHeight = MeasureSpec.getSize(heightMeasureSpec);&nbsp; &nbsp; int myWidth = (int) (parentHeight * 0.5);&nbsp; &nbsp; super.onMeasure(MeasureSpec.makeMeasureSpec(myWidth, MeasureSpec.EXACTLY), heightMeasureSpec);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android