为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

森林海 2019-11-08 14:25:02
如何根据其父布局的大小调整视图的大小。例如,我有一个RelativeLayout可以填满整个屏幕的,并且我想要一个子视图(例如)ImageView占据整个高度,而宽度占整个宽度的1/2?我试图重写所有的onMeasure,onLayout,onSizeChanged,等我无法得到它的工作....
查看完整描述

3 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

我不知道是否有人还在读这个线程,但是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


查看完整回答
反对 回复 2019-11-08
?
守候你守候我

TA贡献1802条经验 获得超10个赞

您可以通过创建自定义View并覆盖onMeasure()方法来解决此问题。如果您始终在xml中的layout_width中使用“ fill_parent”,则传递给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>


查看完整回答
反对 回复 2019-11-08
?
隔江千里

TA贡献1906条经验 获得超10个赞

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


但是,您可以做的是修改measureSpecs,然后使用它们调用super。您的视图将永远不会知道它正在从其父级收到经过修改的消息,并将为您处理所有事情:


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

}


查看完整回答
反对 回复 2019-11-08
  • 3 回答
  • 0 关注
  • 786 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信