Android frameLayout设置高度match parent

frameLayout在xml中高度设置match parent是无效的,必须要在代码中进行动态设置,代码的方式获取高度然后set:

 

 fl_child = view.findViewById(R.id.fl_child);
        Resources resources = this.getResources();
        int childViewHeight = resources.getDisplayMetrics().heightPixels;
        fl_child.getLayoutParams().height = childViewHeight;

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要自定义一个FrameLayout,需要继承FrameLayout类,并在子类中重写构造方法和一些必要的方法,例如onMeasure()方法、onLayout()方法等。 以下是一个简单的自定义FrameLayout的示例: ```java public class MyFrameLayout extends FrameLayout { public MyFrameLayout(Context context) { super(context); } public MyFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public MyFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 在这里可以对View的尺寸进行自定义 // 例如,设置View的宽高比为2:1 int width = MeasureSpec.getSize(widthMeasureSpec); int height = width / 2; int newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, newHeightMeasureSpec); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); // 在这里可以对子View的位置进行自定义 // 例如,将第一个子View放置在左上角 View childView = getChildAt(0); childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight()); } } ``` 在上面的示例中,我们重写了onMeasure()方法,将View的高度设置为宽度的一半,并在onLayout()方法中将第一个子View放置在左上角。 可以在布局文件中使用自定义的MyFrameLayout,例如: ```xml <com.example.MyFrameLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/image" /> </com.example.MyFrameLayout> ``` 这样就可以在自定义的FrameLayout中放置子View,并对其尺寸和位置进行自定义。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值