【发布时间】:2015-08-04 01:30:03
【问题描述】:
我想自定义一个布局并将其变成一个正方形。在 xml 中,我将其 layout_width 和 layout_height 设置为“match_parent”。然后在它的 onMeasure() 方法中,我得到它的高度和宽度的值,并将它们中最短的设置为正方形每一边的值。代码是这样的:
<SquaredRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
/>
public class SquaredRelativeLayout extends RelativeLayout {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if(width > height) {
super.onMeasure(heightMeasureSpec, heightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
}
现在这是我的问题:我需要将此布局中心设置为与其父级水平。但是每次当宽度>高度时,布局都会对齐到其父级的左侧。有没有人怎么解决这个问题的?
【问题讨论】: