java - 关于如何获得2个相同尺寸的组件进行水平线性布局的一些疑问?

标签 java android android-layout android-linearlayout

我是 Android 开发新手,我已经实现了这个简单的水平 LinearLayout ,分为具有相同空间的 2 个部分:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:layout_width="0px"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/btnPlay"
        android:text="View">
    </Button>

    <Button
        android:layout_width="0px"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/btnEdit"
        android:text="Edit">
    </Button>

</LinearLayout>

它工作正常,我得到了这个结果:

enter image description here

这两个部分具有相同的空间。我知道要做到这一点我必须设置:

android:layout_width="0px"
android:layout_weight="1"

在两个组件上。

它工作正常,但为什么呢?将宽度设置为 0px,重量设置为 1 到底是什么意思?这是某种约定吗?

最佳答案

It works fine but why? What exactly means set the width to 0px and the weight to 1?

首先,LinearLayout 将沿 LinearLayout 轴请求的所有特定尺寸相加。在您的情况下,它是一个水平布局,因此它会将布局宽度值相加。在你的例子中,0px + 0px = 0px。

LinearLayout 然后确定剩余多少像素。假设您的设备有 1080p 屏幕。在这种情况下,1080px - 0px = 1080px。

然后,它会将请求的 layout_weight 值相加。如果将 weightSum 放在 LinearLayout 上,则会跳过这部分,因为直接使用 weightSum。就您而言,1 + 1 = 2。

然后,它根据小部件权重总和的比例分配剩余像素 (1080px)。因此,第一个按钮的大小为 1080px * 1/2 = 540px。第二个按钮的大小为 1080px * 1/2 = 540px。

因此,两个按钮的大小相同,宽度为 540px。

关于java - 关于如何获得2个相同尺寸的组件进行水平线性布局的一些疑问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38161842/

相关文章:

java - 安卓工作室模块

Android Studio 无法在设备 : stuck on "Waiting for process: <project>" 上运行应用程序

android - 如何在android中的 View 上方添加阴影

java - 实例化类,toString 术语

JavaScript/Java GWT 与 Rails

java - Antlr4 访客和成员

android - 如何在 Android 的启动器应用程序上叠加信息?

java - Android 将自定义图像设置为标签文本

android - Activity 的背景图片

android - 动态添加 View android