如何设置按钮的高度,使其与宽度相同?



我有几个按钮,应该是正方形。但是我无法将高度设置为与宽度相同。我该怎么做?

我试图用layout_constraintdimensionlatio解决问题,但它不起作用,高度仅为0。

这是代码:

<Button
            android:id="@+id/grid_11"
            style="@style/Widget.AppCompat.Button.Small"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"></Button>

这就是我尝试的:

<Button
            android:id="@+id/grid_11"
            style="@style/Widget.AppCompat.Button.Small"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="1:1"
            android:layout_weight="1"></Button>

高度为" 0"的原因是因为您没有正确设置按钮的约束。设置适当的约束,如下所示。

<Button
        android:id="@+id/grid_11"
        style="@style/Widget.AppCompat.Button.Small"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintDimensionRatio="1:1"/>

这可以通过使用尺寸文件中的值来实现。如果它在res/values文件夹中不存在,请在此处创建一个称为dimens.xml文件的XML文件。然后添加一个尺寸值,说明您要在按钮的高度和宽度上使用的值:

<dimen name="btn_size">100dp</dimen>

然后,您可以将其指定为这样的按钮:

<Button
            android:id="@+id/grid_11"
            style="@style/Widget.AppCompat.Button.Small"
            android:layout_width="@dimen/btn_size"
            android:layout_height="@dimen/btn_size"
            android:layout_weight="1"></Button>

这将在按钮中添加相同的高度宽度。

更改 -

android:layout_width="wrap_content"
android:layout_height="wrap_content"

至 -

android:layout_width="@dimen/square_button_size"
android:layout_height="@dimen/square_button_size"

并添加

<dimen name="square_button_size">50dp</dimen>

in res/values/dimen.xml

如果您不想将其放在约束点(这是最简单的答案),@sirkarreddy已经建议了它) - 子类按钮并覆盖On-MEASER-MEASER函数,以便它始终将其测量本身是一个正方形。没有内置的方式可以在无需黑客攻击的情况下获得您想要的行为。

最新更新