Android 如何设置按钮';s高度,因此它';宽度是多少?
我有几个按钮,应该是正方形的。但我无法将高度设置为与宽度相同。我该怎么做 我试图用layout_constraintDimensionRatio来解决这个问题,但没用,高度只有0 代码如下:Android 如何设置按钮';s高度,因此它';宽度是多少?,android,xml,button,size,Android,Xml,Button,Size,我有几个按钮,应该是正方形的。但我无法将高度设置为与宽度相同。我该怎么做 我试图用layout_constraintDimensionRatio来解决这个问题,但没用,高度只有0 代码如下: <Button android:id="@+id/grid_11" style="@style/Widget.AppCompat.Button.Small" android:layout_width="match_parent"
<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:layout_width="wrap_content"
android:layout_height="wrap_content"
到-
加
<dimen name="square_button_size">50dp</dimen>
50dp
在res/values/dimen.xml中,高度为“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"/>
这可以通过使用dimens文件中的值来实现。如果它不在
res/values
文件夹中,那么在那里创建一个名为dimens.XML
的XML文件。然后添加一个dimen值,说明要用于按钮高度和宽度的值:
<dimen name="btn_size">100dp</dimen>
100dp
然后可以将其指定到按钮,如下所示:
<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>
这将为按钮添加相同的高度和宽度。如果您不想将其放在约束框中(这是最简单的答案,@sirkarredy已经建议过了)-对按钮进行子类化,并覆盖onMeasure函数,以便它始终将自身作为正方形进行测量。没有内置的方法可以在不修改代码的情况下在RelativeLayout或LinearLayout中获得所需的行为。但是如果我不希望按钮具有特定的大小,该怎么办?我希望它适合布局,因此宽度必须与父视图保持匹配。注意:只有父视图是ContrainLayout时,这才有效
<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>