是否有一种方法可以根据我的 xml 中的宽度设置高度?
我有一些线性布局的按钮。按钮的宽度取决于设备,因为它们水平填充屏幕。我想要方形按钮,这是我的问题。 有没有人可以帮助我?
<Button
android:id="@+id/b_0xa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:clickable="false"
android:text="@string/b_0xa" />
最佳答案
要使 View 的高度
等于 View 的宽度
,可以使用ConstraintLayout
app:layout_constraintDimensionRatio="1:1"
1
before :
是宽度
1
after :
是高度
请尝试以下代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Button"/>
</androidx.constraintlayout.widget.ConstraintLayout>
以上代码的输出是:
关于android - 布局宽度等于高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540444/