为了更好地管理android应用的用户界面里的各组件,android提供了布局管理器。通过使用布局管理器,android应用图形用户界面具有良好的平台无关性。推荐使用布局管理器来管理组件的分布、大小,而不是直接设置组件的位置和大小。可以使用布局管理器嵌套布局管理器,即也可作为一个ui组件来使用。
linearlayout可以控制组件横向排列或者纵向排列,内容不会换行,超出屏幕部分将不会显示出来。
学习图解
linearlayout 常用xml属性及方法
【属性一】orientation 设置子组件的排列方式(单选)
xml:android:orientation="horizontal"
horizontal:横向排列
vertical:纵向排列
java :linearlayout.setorientation(linearlayout.vertical);
linearlayout.horizontal横向排列
linearlayout.vertical纵向排列
【属性二】gravity设置子组件的对齐方式(多选)
xml:android:gravity="center"
java :linearlayout.setgravity(gravity.center);
【属性三】baselinealigned 设置子元素基准线对弃,默认为true
基准线:
打开的英语练习本,那条红线就是基准线
xml:android:baselinealigned="false"
java:linearlayout.setbaselinealigned(true);
代码:true
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselinealigned="true"
android:orientation="horizontal">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_red_light"
android:padding="20dp"
android:text="text1"
android:textsize="30sp">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:padding="10dp"
android:text="text2"
android:textsize="16sp">
效果:
【搭配属性三】baselinealignedchildindex linearlayout的基准线以他的第几个子元素为准,下标从0开始
一个linearlayout 里面有很多 textview ,每一个 textview 都有自己的基准线,那么linearlayout可能也是另一个linearlayout的子元素,作为子元素 baselinealignedchildindex 就决定这他的一个基准线
xml:android:baselinealignedchildindex="0"
java:linearlayout.setbaselinealignedchildindex(0);
代码:⭐注意内部的linearlayout,后面将在 第二个linearlayout上添加 baselinealignedchildindex ,搭配 baselinealigned="false" 使用
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:baselinealigned="false"
android:orientation="horizontal">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:text="这是text2"
android:textsize="20sp">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_red_light"
android:text="这是text1"
android:textsize="30sp">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_green_dark"
android:text="这是text2"
android:textsize="15sp">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是text4"
android:textsize="25sp"
android:background="@android:color/holo_orange_light"
>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/black"
android:text="text"
android:textcolor="@android:color/white"
android:textsize="15sp">
效果:
⭐ 总结
默认linearlayout是没有基准线的,从图一和图三的对比可知。
下标从0开始三个子组件,最大index为2,超过2时布局将不显示
这个属性是用来决定当前linearlayout的基准线时以哪个子组件为准的