首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何根据其父视图的尺寸调整Android视图的大小

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

Stack Overflow用户
提问于 2010-01-29 09:30:47
回答 10查看 156.4K关注 0票数 107

如何根据其父布局的大小调整视图的大小。例如,我有一个充满整个屏幕的RelativeLayout,我想要一个子视图,比如ImageView,占据整个高度和一半的宽度?

我试过在onMeasureonLayoutonSizeChanged等上覆盖所有内容,但我无法让它正常工作……

EN

回答 10

Stack Overflow用户

发布于 2010-05-26 03:44:57

您可以通过创建自定义视图并覆盖onMeasure()方法来解决此问题。如果您总是使用"fill_parent“作为xml中的layout_width,那么传入onMeasusre()方法的widthMeasureSpec参数应该包含父对象的宽度。

代码语言:javascript
复制
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将如下所示:

代码语言:javascript
复制
<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>
票数 42
EN

Stack Overflow用户

发布于 2011-11-29 02:18:58

我发现最好不要自己设置测量的尺寸。实际上,父视图和子视图之间需要进行一些协商,您不想重写所有这些code

不过,您可以做的是修改measureSpecs,然后使用它们调用超级。你的视图永远不会知道它正在从它的父级那里得到一个修改过的消息,并且会为你处理所有的事情:

代码语言:javascript
复制
@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);
}
票数 28
EN

Stack Overflow用户

发布于 2010-01-29 10:21:40

在XML上定义布局和视图时,可以将视图的布局宽度和高度指定为wrap_contentfill_parent。占据一半的面积有点困难,但如果你在另一半上有你想要的东西,你可以这样做。

代码语言:javascript
复制
<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.

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2159320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档