等宽高的ImageButton

@SuppressLint("AppCompatCustomView")
public class SquareImageButton extends ImageButton {
    public SquareImageButton(Context context) {
        super(context);
    }

    public SquareImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public SquareImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 1. 先运行默认测量方式,确认好宽高
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 2. 搞事情,根据默认测量好的大小,改为正方形,暂时实现只以宽为参考
        int widthSize = getMeasuredWidth(); // 获取默认测量好的宽度
        int heightSize = widthSize; // 高度改为与宽度同样
        // 3. 重点一步,从新将高宽设给测量值,覆盖原来的值
        setMeasuredDimension(widthSize, heightSize);
    }
}
相关文章
相关标签/搜索