LinearLayout 在布局使用中比较频繁,一般可以设置成horizontal(横向)、vertical(竖向)两个方向,不过LinearLayout还有如下几个重要的属性,了解这几个属性可以让我们更加全面地认识linearLayout的真正功能。
1、weight 属性
weight属性意思是占比,就是占用的空间的大小,其实它的真正意义是剩余空间的占比。比如我们添加两个TextView,其中的text1添加android:layout_weight="1"
,text2添加android:layout_weight="2"
,
举个例子
在开发过程中发现父布局宽度写死,然后其他几个字空间在有限的空间里面隐藏和显示,只要中间的TextView控件添加android:layout_weight="1"属性,则可以实现宽度的自适应显示
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="match_parent"
android:orientation="horizontal">
< ImageView
android:id="@+id/image_1"
android:layout_width="40dp"
android:layout_height="40dp"
src="@drawable/ic_launcher"
android:visible="gone"
/>
< TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1"
android:background="#00FF00"
android:text="text2" />
< ImageView
android:id="@+id/image_2"
android:layout_width="40dp"
android:layout_height="40dp"
src="@drawable/ic_launcher"
< /LinearLayout>
当 image_1隐藏时,textview的宽度则会变大,但是当image_1和image_2都显示时,textview的宽度则会变小,从而实现在有限的100dp的父布局里面实现布局自适应显示