LinearLayout中的重要属性layout_weight

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 则会占满屏幕所有的剩余空间。

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

posted @ 2018-08-29 11:16  &慧&  阅读(600)  评论(0编辑  收藏  举报