【问题标题】:How do I set my button's height so it's the same as the width?如何设置按钮的高度,使其与宽度相同?
【发布时间】:2019-03-23 15:18:18
【问题描述】:

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

我尝试用layout_constraintDimensionRatio解决这个问题,但是没用,高度只有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>

【问题讨论】:

    标签: android xml button size


    【解决方案1】:

    高度为“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"/>
    

    【讨论】:

    • 注意:这只有在父视图是一个 ContraintLayout 时才有效
    【解决方案2】:

    这可以通过使用dimens 文件中的值来实现。如果它不在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>
    

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

    【讨论】:

    • 但是如果我不希望按钮具有特定大小怎么办?我希望它适合布局,所以宽度必须保持 match_parent。
    【解决方案3】:

    改变-

    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>
    

    res/values/dimen.xml

    【讨论】:

      【解决方案4】:

      如果您不想将它放在 ConstraintLayout 中(这是最简单的答案,@SirkarReddy 已经建议了)- 子类 Button 并覆盖 onMeasure 函数,以便它始终将自身测量为正方形。没有内置的方法可以在没有对代码进行一些黑客攻击的情况下在 RelativeLayout 或 LinearLayout 中获得您想要的行为。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-12
        • 2020-12-25
        • 1970-01-01
        • 1970-01-01
        • 2015-06-24
        • 2016-10-14
        • 2013-09-16
        相关资源
        最近更新 更多