一个有最大宽度和高度属性的布局

有时候会遇到一些需要设置最大高度或者宽度的布局,但是常用的布局没有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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值