LinearLayout中的重要属性layout_weight

博客介绍了在Android开发中,使用android:layout_weight属性时,控件宽度不应由android:layout_width决定,0dp是规范写法,dp是指定控件大小等属性的单位。还说明了系统计算控件大小比例的方式,以及通过指定部分控件layout_weight值可实现更好效果,界面适配性好且美观。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android:layout_weight,这个属性允许我们使用比例的方式来指定控件的大小,在屏幕的适配性方面可以起到非常重要的作用。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_first"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.qihui.myapplication10.FirstActivity"
    android:orientation="horizontal">
<EditText
    android:id="@+id/input_message"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:hint="提示信息"/>
    
    <Button
        android:text="ButtonF"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/buttonf"
        android:layout_weight="1"/>

</LinearLayout>

  由于我们使用了 android:layout_weight属性,此时控件的宽度就不应该再由 android:layout_width 来决定,0dp是一种比较规范的写法。另外dp是android中用于指定控件大小,间距等属性的单位。

       系统会把 LinearLayout下所有控件指定的layout_weight值相加,得到一个总值,然后每个控件占大小的比例就是用该控件的layout_weight值 除以刚才算出的总值。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_first"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.qihui.myapplication10.FirstActivity"
    android:orientation="horizontal">
<EditText
    android:id="@+id/input_message"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:hint="提示信息"/>

    <Button
        android:text="ButtonF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonf"/>

</LinearLayout>

  通过指定部分控件 layout_weight值来实现更好的效果。

       这表示Button的宽度仍然按照 wrap_content 来计算,而 EditText 则会占满屏幕所有的剩余空间。

       使用这种方式编写的界面,不仅在各种屏幕的适配方面会非常好,而且看起来也更加舒服。

转载于:https://www.cnblogs.com/huichao1314/p/9553215.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值