【Android】布局文件layout.xml文件使用控件属性android:layout_weight使布局较为美观,以RadioButton为例

发布于:2025-02-10 ⋅ 阅读:(113) ⋅ 点赞:(0)

目录

说明

  简单来说,android:layout_weight为当前控件按比例分配剩余空间。且单个控件该属性的具体数值不重要,而是多个控件的属性值之比发挥作用,例如有2个控件,各自的android:layout_weight的值设为0.5和0.5,或者设置为5和5,布局效果都是各占一半,都是1:1

举例

  本文以RadioButton为例,使用此控件需要搭配RadioGroup,初始版本代码如下:

<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">        

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="仅通知"
        android:textSize="20dp"
        android:textColor="@android:color/black"/>

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自动化"
        android:textSize="20dp"
        android:textColor="@android:color/black"/>
</RadioGroup>

  实现效果如下:
在这里插入图片描述
  喜欢对称放在屏幕中间风格的,给两个RadioButton设置android:layout_weight值为0.5,代码不再赘述,效果图如下:
在这里插入图片描述
  感觉还是不够对称的,希望能够在屏幕两侧有对称的空余,可以随便加些控件如TextView来占个位置,注意,占空控件的宽、高属性android:layout_widthandroid:layout_height设置为wrap_content或者0dp,且RadioButton不设置android:layout_weight属性。 这样占空控件只会分配RadioButton布局好后的剩余空间。代码补充如下:

<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    
    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:layout_gravity="center"/>

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="仅通知"
        android:textSize="20dp"
        android:textColor="@android:color/black"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:layout_gravity="center"/>

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自动化"
        android:textSize="20dp"
        android:textColor="@android:color/black"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:layout_gravity="center"/>
</RadioGroup>

  最终效果如下:
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到