布局宽度等于高度

Twi*_*g90 10 android button android-layout

有没有一种方法让高度取决于我的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" />
Run Code Online (Sandbox Code Playgroud)

Swa*_*yam 0

您可以在 Java 代码中以编程方式轻松完成此操作。

动态获取按钮的宽度[使用int x = mButton.getWidth()],然后使用返回的值设置高度[ mButton.setHeight(x)]。

PS:建议使用LayoutParams来设置任何View的高度和宽度。因此,您应该使用 setLayoutParams(),而不是使用 setHeight()。

mButton.setLayoutParams(new LinearLayout.LayoutParams(x, x));