Android 当layout_高度和layout_宽度设置为不同大小时,如何使自定义视图成方形?

Android 当layout_高度和layout_宽度设置为不同大小时,如何使自定义视图成方形?,android,android-custom-view,Android,Android Custom View,根据我的理解,当用户以像素/dp为单位指定视图高度/宽度时,视图将完全接收规格模式。等级库模式意味着视图必须使用此大小。假设我想确保我的视图保持正方形。如果用户为布局高度和布局宽度设置不同的值,如何实现这一点。覆盖自定义视图的测量,确定最小尺寸,并将宽度和高度设置为最小尺寸 比如: @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthM

根据我的理解,当用户以像素/dp为单位指定视图高度/宽度时,视图将完全接收规格模式。等级库模式意味着视图必须使用此大小。假设我想确保我的视图保持正方形。如果用户为布局高度和布局宽度设置不同的值,如何实现这一点。

覆盖自定义视图的测量,确定最小尺寸,并将宽度和高度设置为最小尺寸

比如:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int specWidth = MeasureSpec.getSize(widthMeasureSpec);
    int specHeight = MeasureSpec.getSize(heightMeasureSpec);
    int lesserDimension = (specWidth > specHeight)?specHeight:specWidth;
    setMeasuredDimension(lesserDimension, lesserDimension);
}