有时候会遇到一些需要设置最大高度或者宽度的布局,但是常用的布局没有maxHeIght或者minHeight属性,所以考虑到自定义一个,具体思路就是在onMeasure中查看是否有设置最大高度或者最大宽度,如果没有则按照默认的进行测量。
1.首先在res/value/attrs中添加属性
<resources> <declare-styleable name="BoundedLayout"> <attr name="layout_maxWidth" format="dimension"></attr> <attr name="layout_maxHeight" format="dimension"></attr> </declare-styleable> </resources>
2.自定义Layout继承FrameLayout,并在构造方法中获取设置的属性:
private void initAttrs(AttributeSet attrs) { TypedArray array = mContext.obtainStyledAttributes(attrs, R.styleable.BoundedLayout); mMaxWidth = array.getDimension(R.styleable.BoundedLayout_layout_maxWidth, -1); mMaxHeight = array.getDimension(R.styleable.BoundedLayout_layout_maxHeight, -1); array.recycle(); }
3.onMesure方法中对最大最小值进行设置:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { /** * 如果没有设置宽高 则默认按照系统的宽高测量方法加载 */ if (mMaxWidth <= -1 && mMaxHeight <= -1) { 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); widthSize = getWidth(widthSize); heightSize = getHeight(heightSize); /** * 把此时的高宽 和模式 设置回去 */ int maxWdithMeasure = MeasureSpec.makeMeasureSpec(widthSize, widthMode); int maxHeightMeasure = MeasureSpec.makeMeasureSpec(heightSize, heightMode); super.onMeasure(maxWdithMeasure, maxHeightMeasure); } // 对宽度进行调整,是否超出最大宽度,超出取最大宽度,没超出,取设置的值 public int getWidth(int width) { if (mMaxWidth <= -1) { return width; } return width <= mMaxWidth ? width : (int) mMaxWidth; } /** * 如果设置的最大高度高于能用的高度 则返回能用的高度 * * @param height * @return */ public int getHeight(int height) { if (mMaxHeight <= -1) { return height; } return height <= mMaxHeight ? height : (int) mMaxHeight; }
代码很简单,附上链接
https://download.csdn.net/download/qq_25238883/11366655