android - 不均匀的 LinearLayout 权重分布

标签 android android-linearlayout

我有一个 LinearLayout,它有四个水平布局的 View 。第一个和最后一个组件是固定大小。对于内部两个 View ,我只想共享可用空间 50:50。我将每个权重都设置为“1”,但是当布局 View 时, View 的大小取决于它们所包含的内容。 Screen shot of the layout. The data is hidden but it shows how offset the views are

这是我的布局 xml 以供引用。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
    <ImageView 
        android:id="@+id/status" 
        android:src="@drawable/white"
        android:paddingRight="10dip" 
        android:layout_height="35dip" 
        android:layout_width="35dip">
    </ImageView>
    <TextView android:id="@+id/name" 
        android:text="Name" 
        android:layout_height="fill_parent" 
        android:layout_toRightOf="@id/status" 
        android:layout_width="wrap_content" 
        android:layout_weight="1" 
        android:textSize="25dip">
    </TextView>
    <TextView android:id="@+id/description"
        android:text="Description"
        android:layout_toRightOf="@id/name" 
        android:layout_height="fill_parent"
        android:layout_width="wrap_content"
        android:layout_weight="1"
        android:textSize="25dip">
    </TextView>
    <TextView android:id="@+id/time" 
        android:text="Time" 
        android:layout_width="wrap_content" 
        android:layout_height="fill_parent"
        android:layout_toRightOf="@id/description" 
        android:textSize="25dip">
    </TextView>
</LinearLayout>

显然这些不是实际的列名称,但出于保护隐私的目的我更改了它们。此布局由 ListView 使用,它将每个 View 的文本更改为其呈现的任何值。名称和描述字段应该排成一行,因为它们都占剩余屏幕的 50%,但当名称较长时,描述会向右移动。为什么?

最佳答案

要考虑权重,布局维度需要为0(零)

<TextView android:id="@+id/name" 
    android:text="Name" 
    android:layout_height="fill_parent"  
    android:layout_width="0dip" 
    android:layout_weight="1" 
    android:textSize="25dip">
</TextView>

我还建议将您的体重加起来等于 1(并使用分数)或 100。

因此,您可以为每个 View 使用 50 或 .5 而不是 1。 LinearLayout 代码将适用于任何权重总和,但如果您想稍后使用其他部分修改 View ,这将变得困难。

此外,如果您不使用相对布局,请去掉 toRightOf 属性。少即是多。

关于android - 不均匀的 LinearLayout 权重分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6117240/

相关文章:

java - 如何在代码中将 View 添加到线性布局的顶部?

android - LinearLayout 用给定的空间值均匀填充 TextView

android - 如何在 fragment 转换中删除 fragment 被替换的 fragment ?

android - 样式多重继承

java - 发送 0xFF 并计算带符号字节的 CRC - WriteSingleCoil & ModBUS & Java & Android -

android - 当键盘出现时, View 在 xamarin 表单 android 中向上移动

android - 滑动抽屉下方的按钮正在注册点击

java - 框架布局 : View Arrrangement and Null Pointer Exception

android - RecyclerView 没有完全展开以显示所有元素

java - 嵌套的 LinearLayouts LayoutTransition 动画在移除子项时跳转