layout_weight的使用说明

   近期学习了Mars老师的视频,看了十二课的有关layout_weight的讲解,就做了些总结。

    layout_weight用于分配剩余的布局空间。

  1. 首先,先看段代码,它定义了两个textview控件                                                                                                                                                          
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#00ff00"
        android:text="first" />
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0000ff"
        android:text="seconed"/>

剩余的布局空间就是红色部分。

        2.加入layout_weight代码

 <LinearLayout 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="#ff0000">
       <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#00ff00"
        android:text="first" />
    
       <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0000ff"
        android:text="seconed"/>
       </LinearLayout>
       
    <LinearLayout 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="#ff0000">
       <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#00ff00"
        android:text="first" />
    
       <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#0000ff"
        android:text="seconed"/>
       </LinearLayout>

code中有android:layout_weight="1"这是说每个text平分红色空间的1/2;另外从图中可以看出,两个textview平分了剩余的红色空间,需要明白的是layout_weight平分的是红色空间

PS:如果设置android:layout_weight="1"另一个为android:layout_weight="2",则一个占据红色空间的1/3,另一个占据2/3.

要想两个textview不只是占据红色的剩余空间,而是拥有相同的空间,仅需将android:layout_width设为0.另外将android:layout_weight="1"即可。

(新手,有什么不对的请指正)

原文地址:https://www.cnblogs.com/mercuryli/p/4410079.html