在Android开发中,我们经常需要自定义View来满足特定的需求。其中,修改FrameLayout的高宽通常是一个常见的需求。本文将介绍如何自定义FrameLayout并修改其高宽。
FrameLayout简介
FrameLayout是Android中常用的布局容器之一,它可以包含多个子View,并按照它们在布局中的顺序进行叠加。每个子View可能会占据不同的位置和大小,但它们都会显示在FrameLayout的左上角。
自定义FrameLayout
要修改FrameLayout的高宽,我们可以自定义一个继承自FrameLayout的类,并在其中重写onMeasure方法。onMeasure方法用于测量子View的大小并设置布局容器的大小。
话不多说,直接上代码。
MaxLayout.java
import android.util.DisplayMetrics; import android.view.ViewGroup; import android.widget.FrameLayout; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.WindowManager; /** * * 可以设置最大宽高的FrameLayout * 默认优先比例设置 * 不支持参数小于零 * */ public class MaxLayout extends FrameLayout { private float mMaxHeightRatio = -1f;// 优先级高 private float mMaxHeight = -1f;// 优先级低 private float mMaxWidthRatio = -1f;// 优先级高 private float mMaxWidth = -1f;// 优先级低 private int parentWidth; private int parentHeight; private boolean firstHeightRatio = true;//高默认优先比例设置 private boolean firstWidthRatio = true;//宽默认优先比例设置 public MaxLayout(Context context) { super(context); } public MaxLayout(Context context, AttributeSet attrs) { super(context, attrs); initAttrs(context, attrs); } public MaxLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initAttrs(context, attrs); } private void initAttrs(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MaxLayout); if(a!=null){ firstHeightRatio = a.getBoolean(R.styleable.MaxLayout_first_ratio_height,true); firstWidthRatio = a.getBoolean(R.styleable.MaxLayout_first_ratio_width,true); mMaxHeightRatio = a.getFloat(R.styleable.MaxLayout_max_height_ratio, -1f); mMaxHeight = a.getDimension(R.styleable.MaxLayout_max_height, -1f); mMaxWidthRatio = a.getFloat(R.styleable.MaxLayout_max_width_ratio, -1f); mMaxWidth = a.getDimension(R.styleable.MaxLayout_max_width, -1f); a.recycle(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { initParentWH(); initWH(); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize <= mMaxHeight ? heightSize : (int) mMaxHeight, heightMode); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize <= mMaxWidth ? widthSize : (int) mMaxWidth, widthMode); super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec); } /** * 计算需要设置的宽高 */ private void initWH() { if((firstHeightRatio && mMaxHeightRatio > 0) || (!firstHeightRatio && mMaxHeight < 0)){ mMaxHeight = mMaxHeightRatio * parentHeight; } if((firstWidthRatio && mMaxWidthRatio > 0) || (!firstWidthRatio && mMaxWidth < 0)){ mMaxWidth = mMaxWidthRatio * parentWidth; } } /** * 获取父控件的宽高 */ private void initParentWH() { ViewGroup parent = (ViewGroup) getParent(); if(null != parent){ parentWidth = parent.getWidth(); parentHeight = parent.getHeight(); }else { WindowManager wm = (WindowManager) getContext() .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics dm = new DisplayMetrics(); if (wm != null) { wm.getDefaultDisplay().getMetrics(dm); parentWidth = dm.widthPixels; parentHeight = dm.heightPixels; } } } }
attrs.xml
<declare-styleable name="MaxLayout"> <attr name="max_height_ratio" format="float"/> <attr name="max_height" format="dimension"/> <attr name="max_width_ratio" format="float"/> <attr name="max_width" format="dimension"/> <attr name="first_ratio_height" format="boolean"/> <attr name="first_ratio_width" format="boolean"/> </declare-styleable>
在实际项目开发中,如果在Scrollview(也限定了宽高)中嵌套了限定宽高的Framelayout,可能会出现Framelayout里面的子view最底部的显示不出来的问题,那么就需要对上面的代码进行一定的改动。
思路:
- Framelayout 的高度应该是所有子view的高度的和;
- 由于Framelayout动态添加子view的时候如果不指定坐标的话或叠在一起,所以一般都会指定坐标;
- 对Framelayout里面的子view进行遍历,获取Y坐标最大的子view和该view的高度(也要考虑他的Margin值);
- Framelayout 的高度实际上就是最大Y坐标的子view的高度+最大Y坐标的值。
同时也就解决了FrameLayout添加子view显示不全或者显示个数不完整的问题。
/** * 可以设置最大宽高的FrameLayout */ public class MaxFrameLayout extends FrameLayout { private static final String TAG = "MaxFrameLayout"; private int mMaxHeight = 0; private int mMaxWidth = 0; public MaxFrameLayout(Context context) { super(context); } public MaxFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public MaxFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public MaxFrameLayout(Context context, int maxWidth, int maxHeight) { super(context); mMaxWidth = maxWidth; mMaxHeight = maxHeight; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int realHeight = Math.max(getParentHeight(getChildCount()), mMaxHeight); Log.e(TAG, "onMeasure heightSize " + heightSize + " realHeight " + realHeight + " mMaxHeight " + mMaxHeight); int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(heightSize, realHeight), heightMode); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(widthSize, mMaxWidth), widthMode); super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec); } /** * 根据子view的坐标确定getParent的高度 * @param size * @return */ public int getParentHeight(int size) { int height = 0; int maxIndex = 0; int maxY = 0;//获取最底部view的Y坐标 for (int i = 0; i < size; i++) { View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); int y = (int) child.getY(); maxY = Math.max(y, maxY); if(maxY == y) { maxIndex = i; final int hPadding = lp.topMargin + lp.bottomMargin; height = maxY + lp.height + hPadding; } Log.d(TAG, "maxIndex " + maxIndex + " maxY " + maxY + " height " + height); } return height; } }
其他实现方式。
一、自定义FrameLayout
public class CustomFrameLayout extends FrameLayout { public CustomFrameLayout(Context context) { super(context); } public CustomFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CustomFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width = 0; int height = 0; // 计算子View的宽度和高度 for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); measureChild(child, widthMeasureSpec, heightMeasureSpec); width = Math.max(width, child.getMeasuredWidth()); height = Math.max(height, child.getMeasuredHeight()); } // 根据测量模式设置最终的宽度和高度 if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else if (widthMode == MeasureSpec.AT_MOST) { width = Math.min(width, widthSize); } if (heightMode == MeasureSpec.EXACTLY) { height = heightSize; } else if (heightMode == MeasureSpec.AT_MOST) { height = Math.min(height, heightSize); } // 设置最终的宽度和高度 setMeasuredDimension(width, height); } }
使用自定义FrameLayout
使用自定义的FrameLayout和使用普通的FrameLayout没有太大的区别,只需要在布局文件中使用我们定义的CustomFrameLayout即可。
<com.example.CustomFrameLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 子View的布局 --> </com.example.CustomFrameLayout>
二、自定义FrameLayout
MaxLayout.java
package com.xj.maxlayout; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.IntDef; import android.util.AttributeSet; import android.util.Log; import android.widget.FrameLayout; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * This layout could set maxWidth,maxHeight,ratio * <p> * Created by jun xu on 19-2-1. */ public class MaxLayout extends FrameLayout { private static final String TAG = "MaxLayout"; public static final float DEF_VALUE = -1f; public static final int W_H = 1; public static final int H_W = 2; public static final int STANDRAD = 0; private Context mContext; private float mMaxHeight = -1f; private float mMaxWidth = -1f; private @RatioStandrad int mRatioStandrad; private float mRatio; @IntDef({STANDRAD, W_H, H_W}) @Retention(RetentionPolicy.SOURCE) public @interface RatioStandrad { } public MaxLayout(Context context) { this(context, null, 0); } public MaxLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MaxLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; initAttrs(attrs); } private void initAttrs(AttributeSet attrs) { TypedArray ta = mContext.obtainStyledAttributes(attrs, R.styleable.MaxLayout); mMaxHeight = ta.getDimension(R.styleable.MaxLayout_ml_maxheight, DEF_VALUE); mMaxWidth = ta.getDimension(R.styleable.MaxLayout_ml_maxWidth, DEF_VALUE); mRatioStandrad = ta.getInt(R.styleable.MaxLayout_ml_ratio_standard, STANDRAD); mRatio = ta.getFloat(R.styleable.MaxLayout_ml_ratio, 0); ta.recycle(); } public void setMaxHeight(float maxHeight) { mMaxHeight = maxHeight; } public void setMaxWidth(float maxWidth) { mMaxWidth = maxWidth; } public void setRatioStandrad(int ratioStandrad) { mRatioStandrad = ratioStandrad; } /** * only mRatioStandrad is {@link #W_H, #H_W},this is effective * * @param ratio */ public void setRatio(float ratio) { mRatio = ratio; } public float getMaxHeight() { return mMaxHeight; } public float getMaxWidth() { return mMaxWidth; } public int getRatioStandrad() { return mRatioStandrad; } public float getRatio() { return mRatio; } public void clearMaxWidthFlag() { mMaxWidth = -1f; } public void clearMaxHeightFlag() { mMaxHeight = -1f; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 是否设置了比例 boolean setRatio = isSetRatio(); // 没有设置最大宽度,高度,宽高比例,不需要调整,直接返回 if (mMaxWidth <= DEF_VALUE && mMaxHeight <= DEF_VALUE && !setRatio) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } // 拿到原来宽度,高度的 mode 和 size int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); Log.d(TAG, "origin onMeasure: widthSize =" + widthSize + "heightSize = " + heightSize); if (mRatioStandrad == W_H) { // 当模式已宽度为基准 widthSize = getWidth(widthSize); if (mRatio >= 0) { heightSize = (int) (widthSize * mRatio); } heightSize = getHeight(heightSize); int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY); int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec); } else if (mRatioStandrad == H_W) { // 当模式已高度为基准 heightSize = getHeight(heightSize); if (mRatio >= 0) { widthSize = (int) (heightSize * mRatio); } widthSize = getWidth(widthSize); int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY); super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec); } else { // 当没有设定比例的时候 widthSize = getWidth(widthSize); heightSize = getHeight(heightSize); int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec); } Log.d(TAG, "adjust onMeasure: widthSize =" + widthSize + "heightSize = " + heightSize); } // 对宽度进行调整,是否超出最大宽度,超出取最大宽度,没超出,取原来的值 private int getWidth(int widthSize) { if (mMaxWidth <= DEF_VALUE) { return widthSize; } return widthSize <= mMaxWidth ? widthSize : (int) mMaxWidth; } // 对高度进行调整,是否超出最大高度,超出取最大高度,没超出,取原来的值 private int getHeight(int heightSize) { if (mMaxHeight <= DEF_VALUE) { return heightSize; } return heightSize <= mMaxHeight ? heightSize : (int) mMaxHeight; } private boolean isSetRatio() { return mRatio > 0f && (mRatioStandrad == W_H || mRatioStandrad == H_W); } }
使用说明
常用的自定义属性
<declare-styleable> <attr name="ml_maxWidth" format="dimension" /> <attr name="ml_maxheight" format="dimension" /> <attr name="ml_ratio" format="float" /> <attr name="ml_ratio_standard"> <enum name="w_h" value="1" /> <enum name="h_w" value="2" /> </attr> </declare-styleable>
指定最大宽度,高度
指定最大宽度,最大高度,我们值需要使用 ml_maxWidth,ml_maxheight 属性即可,当然我们也可以同时指定最大宽度和最大高度。如下
<com.xj.maxlayout.MaxLayout android:layout_width="match_parent" android:layout_height="100dp" android:layout_marginTop="15dp" android:background="@android:color/holo_blue_light" app:ml_maxWidth="200dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="10dp" android:text="指定最大宽度,指定最大宽度,指定最大宽度" /> </com.xj.maxlayout.MaxLayout> <com.xj.maxlayout.MaxLayout android:layout_width="200dp" android:layout_height="match_parent" android:layout_marginTop="15dp" android:background="@android:color/holo_blue_light" app:ml_maxheight="200dp"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:padding="10dp" android:text="指定最大高度" /> </com.xj.maxlayout.MaxLayout> <com.xj.maxlayout.MaxLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginTop="15dp" android:background="@android:color/holo_blue_light" app:ml_maxWidth="200dp" app:ml_maxheight="150dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="10dp" android:text="同时指定最大宽度和最大高度" /> </com.xj.maxlayout.MaxLayout>
指定宽高比
指定宽高比,我们需要设置两个属性,ml_ratio_standard 和 ml_ratio。ml_ratio_standard 有两个值,w_h 代表已宽度为基准,h_w 代表已高度为基准。
<com.xj.maxlayout.MaxLayout android:id="@+id/ml_1" android:layout_width="100dp" android:layout_height="wrap_content" android:background="@color/colorAccent" app:ml_ratio="2.0" app:ml_ratio_standard="w_h"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@mipmap/jsy03" /> </com.xj.maxlayout.MaxLayout>
比如,我们要指定宽度是高度的某个比例的时候,如,宽度是高度的 0.8,可以这样写
<com.xj.maxlayout.MaxLayout android:id="@+id/ml_2" android:layout_width="match_parent" android:layout_height="200dp" android:layout_marginLeft="20dp" android:layout_toRightOf="@id/ml_1" android:background="@android:color/holo_blue_light" app:ml_ratio="0.8" app:ml_ratio_standard="h_w"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@mipmap/jsy04" /> </com.xj.maxlayout.MaxLayout>
当然,也可以同时指定比例和最大宽度,高度。
<com.xj.maxlayout.MaxLayout android:id="@+id/ml_03" android:layout_width="match_parent" android:layout_height="220dp" android:layout_below="@id/ml_1" android:layout_marginTop="15dp" android:background="@android:color/holo_blue_light" app:ml_maxWidth="150dp"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@mipmap/jsy05" /> </com.xj.maxlayout.MaxLayout>
原理介绍
原理其实很简单,对自定义 View 有基本了解的人都知道,View 的宽度和高度,是在 onMeasure 方法中进行测量的,他们的大小受 MeasureSpec 的影响。既然如此,那么我们在继承 FrameLayout,重写它的 onMeasure 方法。在 onMeasure 方法中根据我们指定的最大宽度,高度和比例对 MeasureSpec 进行调整即可。
思路大概如下
- 没有设置最大宽度,高度,宽高比例,不需要调整,直接返回
- 先拿到原来的 mode 和 size,暂存起来
- 根据宽高的比例进行相应的调整
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 是否设置了比例 boolean setRatio = isSetRatio(); // 没有设置最大宽度,高度,宽高比例,不需要调整,直接返回 if (mMaxWidth <= DEF_VALUE && mMaxHeight <= DEF_VALUE && !setRatio) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } // 拿到原来宽度,高度的 mode 和 size int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); Log.d(TAG, "origin onMeasure: widthSize =" + widthSize + "heightSize = " + heightSize); if (mRatioStandrad == W_H) { // 当模式已宽度为基准 widthSize = getWidth(widthSize); if (mRatio >= 0) { heightSize = (int) (widthSize * mRatio); } heightSize = getHeight(heightSize); int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY); int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec); } else if (mRatioStandrad == H_W) { // 当模式已高度为基准 heightSize = getHeight(heightSize); if (mRatio >= 0) { widthSize = (int) (heightSize * mRatio); } widthSize = getWidth(widthSize); int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY); super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec); } else { // 当没有设定比例的时候 widthSize = getWidth(widthSize); heightSize = getHeight(heightSize); int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec); } Log.d(TAG, "adjust onMeasure: widthSize =" + widthSize + "heightSize = " + heightSize); }
我们来看一下,有三种模式:
- 当模式已宽度为基准的时候,我们首先对宽度进行调整,是否超出最大宽度,超出取最大宽度,没超出,取原来的值。接着,高度按照 mRatio 进行调整,接着判断高度是否超出最大高度,超出取最大高度,没超出,取原来的值。最后,根据相应的 size,mode 生成相应的 MeasureSpec
- 当模式已高度为基准的时候,我们首先对高度进行调整,是否超出最大高度,超出取最大高度,没超出,取原来的值。接着,宽度按照 mRatio 进行调整,接着判断宽度是否超出最大宽度,超出取最大宽度,没超出,取原来的值。最后,根据相应的 size,mode 生成相应的 MeasureSpec
- 当模式是默认,没有指定宽度或者高度作为基准的时候,直接判断宽高度是否超出最大的宽高度,制定相应的 MeasureSpec 即可。
三、自定义FrameLayout
完整项目示例Git仓库
package com.example.jokerlee.custommaxsizeframelayout; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.widget.FrameLayout; /** * Created by jokerlee on 16-3-14. */ public class CustomFramlayout extends FrameLayout { private static final String TAG = "CustomFramlayout"; private static final boolean DEBUG = false; public CustomFramlayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(),attrs); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams ? new LayoutParams((LayoutParams)p):new LayoutParams(p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams; } @Override protected void onMeasure(int widthSpec, int heightSpec) { final int widthMode = MeasureSpec.getMode(widthSpec); final int heightMode = MeasureSpec.getMode(heightSpec); if (DEBUG && widthMode != MeasureSpec.AT_MOST) { Log.w(TAG, "onMeasure: widthSpec " + MeasureSpec.toString(widthSpec) + " should be AT_MOST"); } if (DEBUG && heightMode != MeasureSpec.AT_MOST) { Log.w(TAG, "onMeasure: heightSpec " + MeasureSpec.toString(heightSpec) + " should be AT_MOST"); } final int widthSize = MeasureSpec.getSize(widthSpec); final int heightSize = MeasureSpec.getSize(heightSpec); int maxWidth = widthSize; int maxHeight = heightSize; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.maxWidth > 0 && lp.maxWidth < maxWidth) { maxWidth = lp.maxWidth; } if (lp.maxHeight > 0 && lp.maxHeight < maxHeight) { maxHeight = lp.maxHeight; } } final int wPadding = getPaddingLeft() + getPaddingRight(); final int hPadding = getPaddingTop() + getPaddingBottom(); maxWidth -= wPadding; maxHeight -= hPadding; int width = widthMode == MeasureSpec.EXACTLY ? widthSize : 0; int height = heightMode == MeasureSpec.EXACTLY ? heightSize : 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int childWidthSpec = makeChildMeasureSpec(maxWidth, lp.width); final int childHeightSpec = makeChildMeasureSpec(maxHeight, lp.height); child.measure(childWidthSpec, childHeightSpec); width = Math.max(width, Math.min(child.getMeasuredWidth(), widthSize - wPadding)); height = Math.max(height, Math.min(child.getMeasuredHeight(), heightSize - hPadding)); } setMeasuredDimension(width + wPadding, height + hPadding); } private int makeChildMeasureSpec(int maxSize, int childDimen) { final int mode; final int size; switch (childDimen) { case LayoutParams.WRAP_CONTENT: mode = MeasureSpec.AT_MOST; size = maxSize; break; case LayoutParams.MATCH_PARENT: mode = MeasureSpec.EXACTLY; size = maxSize; break; default: mode = MeasureSpec.EXACTLY; size = Math.min(maxSize, childDimen); break; } return MeasureSpec.makeMeasureSpec(size, mode); } public static class LayoutParams extends FrameLayout.LayoutParams { @ViewDebug.ExportedProperty(category = "layout") public int maxWidth; @ViewDebug.ExportedProperty(category = "layout") public int maxHeight; public LayoutParams(ViewGroup.LayoutParams other) { super(other); } public LayoutParams(LayoutParams other) { super(other); maxWidth = other.maxWidth; maxHeight = other.maxHeight; } public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); final TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.CustomFrameLayoutAttr, 0, 0); maxWidth = a.getDimensionPixelSize( R.styleable.CustomFrameLayoutAttr_layout_maxWidth, 0); maxHeight = a.getDimensionPixelSize( R.styleable.CustomFrameLayoutAttr_layout_maxHeight, 0); a.recycle(); } } }
使用:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:custom_attr="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.jokerlee.custommaxsizeframelayout.MainActivity"> <com.example.jokerlee.custommaxsizeframelayout.CustomFramlayout android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" custom_attr:layout_maxWidth="50dp" custom_attr:layout_maxHeight="30dp"> <ImageView android:layout_width="350dp" android:layout_height="330dp" android:layout_gravity="center" android:background="@color/material_blue_grey_800"/> </FrameLayout> </com.example.jokerlee.custommaxsizeframelayout.CustomFramlayout> </RelativeLayout>
attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CustomFrameLayoutAttr"> <attr name="layout_maxWidth" format="dimension"/> <attr name="layout_maxHeight" format="dimension"/> </declare-styleable> </resources>