【问题标题】:How to create a square layout and set it center horizontally如何创建方形布局并将其设置为水平居中
【发布时间】: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);
        }
    }
}

现在这是我的问题:我需要将此布局中心设置为与其父级水平。但是每次当宽度>高度时,布局都会对齐到其父级的左侧。有没有人怎么解决这个问题的?

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    SquaredRelativeLayout 的父级中使用 android:gravity="center"

    在您的SquaredRelativeLayout 中使用android:layout_centerInParent="true"(而不是android:layout_centerHorizontal="true"

    【讨论】:

    • 其实我为SquareLayout包装了一个FrameLayout,并将layout_gravity设置为center_horizo​​nal,终于成功了。 android:layout_centerInParent="true" 在我的情况下不起作用。
    • 我假设您将其包装到另一个 RelativeLayout 中(因此是 android:layout_centerInParent="true" 解决方案)。如果您的包装器是FrameLayout(并且使用您设置子级重力的方法),那么您需要设置android:layout_gravity="center"android:layout_gravity="center_horizontal|center_vertical"。将其设置为 center_horizo​​ntal 是不够的,它不会在所有情况下看起来都正确。
    【解决方案2】:

    在你的父布局中使用 android:gravity="center"。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 2012-05-30
      • 2014-03-08
      • 1970-01-01
      • 2014-01-05
      相关资源
      最近更新 更多