有的时候需要使某一个布局宽度和高度一样,可以自定义一个布局来实现:
public class SquareLayout extends RelativeLayout{
public SquareLayout(Context context) {
super(context);
}
public SquareLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
int childWidth = getMeasuredWidth();//得到宽度
//高度和宽度一样
heightMeasureSpec = widthMeasureSpec = MeasureSpec
.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {//分发事件
return false;
}
}