Android LinearLayout权重布局

Laughing
2020-12-03 / 0 评论 / 1,387 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年03月18日,已超过341天没有更新,若内容或图片失效,请留言反馈。

Android开发时,我们经常使用ListView展示一些附属信息,比如文章标题下,可能显示作者、发布日期等信息。像人名可能比较短,而对于年月日时分秒的这种日期格式,显示就比较长,所以我们可以通过控制LinearLayout里面的权重,分配不同控件的宽度。

<!--    单据附属信息-->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical">
    <!--收集人-->
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:gravity="center_vertical">
        <ImageView
            android:layout_width="16sp"
            android:layout_height="16sp"
            android:background="@drawable/list_item_user" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textViewCollectedByName"
            android:text="@string/str_const_collected_by"
            android:textSize="@dimen/font_16"
            android:ellipsize="end"/>
    </LinearLayout>
    <!-- 收集时间-->
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:gravity="center_vertical">
        <ImageView
            android:layout_width="16sp"
            android:layout_height="16sp"
            android:background="@drawable/list_item_time" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/str_const_collect_time"
            android:id="@+id/textViewCollectedTime"
            android:textSize="@dimen/font_16"
            android:ellipsize="end"/>
    </LinearLayout>
    <!--科室-->
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="4"
        android:gravity="center_vertical">
        <ImageView
            android:layout_width="16sp"
            android:layout_height="16sp"
            android:background="@drawable/list_item_department" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/str_const_depart"
            android:id="@+id/textViewDepartmentName"
            android:textSize="@dimen/font_16"
            android:ellipsize="end"
            android:maxLines="1"/>
    </LinearLayout>

</LinearLayout>

实现权重,主要注意两个参数

android:layout_width="0dp"android:layout_weight="3"

$$ 控件1宽度 = 控件1权重/(控件1权重+控件2权重+...控件n权重) $$

每个控件的占比,等于控件的权重/所有控件权重的和。

24

评论 (0)

取消
  1. 头像
    帅的太低调
    MacOS · Safari

    多谢站长

    回复