首页 > 解决方案 > 我正在使用 Android Studio 中的布局

问题描述

我是 Android 新手,我正在设计一个布局,使用LinearLayout我希望所有三个buttonsLinearLayout. 我通过给它们相等来做到这一点,width但它们并没有覆盖整个长度。有更简单的方法吗?

标签: androidxml

解决方案


欢迎来到 Android 开发。我确信这可能是一个重复的问题,并建议您在提出新问题之前先搜索以前的答案。

但是让我告诉你如何实现这是一个简单的weight布局应用程序

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:weightSum="3">
        
        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Button 1"
            android:layout_weight="1"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Button 2"
            android:layout_weight="1"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Button 3"
            android:layout_weight="1"
            />
        
        
        
    </LinearLayout>
    

</androidx.constraintlayout.widget.ConstraintLayout>

正如您在上面看到的,weightSum告诉线性布局下面布局中项目的总重量

android:layout_weight="1"是布局中每个元素的权重。所以有三个按钮,每个按钮的权重为 1,这增加了线性布局的 3。所以每个按钮将被分配相同的空间。您可以使用权重为线性布局内的不同视图提供不同的空间。您可以保留 weightSum 属性,线性布局也可以根据孩子的权重总和自行计算。

所以你看到这是一种基于视图承载的权重的相对间距。希望这对您以及您期望知道的内容有所帮助。

编辑:正如 Primoz 所指出的,最好有android:layout_width = "0dp"这样你的团队或其他人可以更好地理解宽度控制视图。


推荐阅读