Android layout

    xiaoxiao2022-06-29  49

    这篇文档主要讲一下layout_weight。给组件添加这个属性时,有一点需要注意,在Android studio中,Design中显示的布局会和手机上运行时显示的不一样,不要被Design蒙骗。

    先上一段局部布局代码,和一张手机界面截图

    局部代码

        <TextView         style="?android:listSeparatorTextViewStyle"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="@string/crime_details_label"         />     <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginLeft="16dp"         android:layout_marginRight="16dp"         >         <Button             android:id="@+id/crime_date"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_weight="1"             />         <CheckBox             android:id="@+id/crime_solved"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_weight="1"             android:text="@string/crime_solved_label"             />     </LinearLayout> </LinearLayout>

     

     

     

    手机界面截图

    从这些信息中,我们可以发现,当LinearLayout中的组件android:layout_width=”wrap_content”时,即便两个android:layout_weight都等于1,从手机上可以看到,比例并不一样,如果从Android studio Design上看呢?

     

    Android studio Design

     

     

    大家可以发现,是一样的,到底哪个是对的呢?理论上来说是手机,下面我就要来讲解一下layout_weight属性的原理。

    LinearLayout是分两个步骤来设置属性宽度的,第一步是查看layout_width的属性值,也就是说它会优先考虑layout_width的属性值,第二步是根据layout_weight属性值进行额外的空间分配,通俗点说,只要layout_width发话了,就全听layout_width的(其实也不是,layout_weight会有影响),如果layout_width没有发话,两个layout_width的值被设置为0dp,

    布局按照第二步的设置来安排。

    下面我们就来这么做,把layout_width设置成0dp,两个组件的layout_weight还都是1不变,上代码,Design图,手机界面截图。

    局部代码

     

      <TextView         style="?android:listSeparatorTextViewStyle"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="@string/crime_details_label"         />     <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginLeft="16dp"         android:layout_marginRight="16dp"         >         <Button             android:id="@+id/crime_date"             android:layout_width="0dp"             android:layout_height="wrap_content"             android:layout_weight="1"             />         <CheckBox             android:id="@+id/crime_solved"             android:layout_width="0dp"             android:layout_height="wrap_content"             android:layout_weight="1"             android:text="@string/crime_solved_label"             />     </LinearLayout> </LinearLayout>

     

     

    Android studio Design:

    当然,它还是保持不变。

     

     

    手机界面截图

     

    通过这两个实验,我们知道它的属性设置是有优先级的。

    转载请注明原文地址: https://ju.6miu.com/read-1124746.html

    最新回复(0)