android - 布局宽度等于高度

标签 android android-layout button

是否有一种方法可以根据我的 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>

以上代码的输出是:

enter image description here

关于android - 布局宽度等于高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540444/

相关文章:

Java - 将分钟和秒更改为时间格式? (毫米:ss)

android - 如何使用现有的自定义主题在 XML 中隐藏 Activity 的标题栏

android - 使用 Google 地方信息 API

android - 如何在旧的安卓设备上支持 Material Design

css - 使用 "Sliding Doors"设计输入按钮的样式

android - 按下按钮时如何更改文本颜色?

java - Android 从 URL 加载到位图

list - flutter 开关按钮未更新

android - 覆盖 Activity 中的后退按钮操作

c# - 在 ControlTemplate 中设置按钮图像