如何根据其父布局的大小调整视图的大小。例如,我有一个充满整个屏幕的RelativeLayout
,我想要一个子视图,比如ImageView
,占据整个高度和一半的宽度?
我试过在onMeasure
、onLayout
、onSizeChanged
等上覆盖所有内容,但我无法让它正常工作……
发布于 2010-05-26 03:44:57
您可以通过创建自定义视图并覆盖onMeasure()方法来解决此问题。如果您总是使用"fill_parent“作为xml中的layout_width,那么传入onMeasusre()方法的widthMeasureSpec参数应该包含父对象的宽度。
public class MyCustomView extends TextView {
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth / 2, parentHeight);
}
}
您的XML将如下所示:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
class="com.company.MyCustomView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
发布于 2011-11-29 02:18:58
我发现最好不要自己设置测量的尺寸。实际上,父视图和子视图之间需要进行一些协商,您不想重写所有这些code。
不过,您可以做的是修改measureSpecs,然后使用它们调用超级。你的视图永远不会知道它正在从它的父级那里得到一个修改过的消息,并且会为你处理所有的事情:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int myWidth = (int) (parentHeight * 0.5);
super.onMeasure(MeasureSpec.makeMeasureSpec(myWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
}
发布于 2010-01-29 10:21:40
在XML上定义布局和视图时,可以将视图的布局宽度和高度指定为wrap_content
或fill_parent
。占据一半的面积有点困难,但如果你在另一半上有你想要的东西,你可以这样做。
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1" />
<ImageView android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1" />
</LinearLayout>
赋予两个事物相同的权重意味着它们将拉伸以占据相同比例的屏幕。有关布局的详细信息,请参阅the dev docs.
https://stackoverflow.com/questions/2159320
复制相似问题