在android中,任何一种布局都可以通过两种方式来实现,一种是XML,另一种是Java代码
线性布局(LinearLayout)
是将其中的组件按照水平或垂直的方向排列
两个重要属性:orientation(必备属性),weight
1.使用格式
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
控件列表
</LinearLayout
2.常用属性
orientation 布局排列方式
- vertical 默认-垂直排列
- horizontal 水平排列
gravity 布局管理器中组件的显示位置
- top
- left
- bottom
- 可以组合使用
layout_gravity 控制该组件在父容器里的对齐方式
layout_weight 布局宽度 layout_height布局高度
- 数字(通常不直接写)
- wrap_content 组件实际大小
- match_parent 与父容器同宽
backgrount 布局背景
- 为该组件设置一个背景图片
- 或者颜色覆盖(
#
ff0000)
id 为该组件设置一个资源id,在java文件中可以通过findViewById(id)找到该组件@+id/唯一标识符
3.Weight(权重)按比例划分剩余空间
均等分布,全部加上:android:layout_weight=“1”
剩余空间全给一个:在其上加上:android:layout_weight=“1”
如要创建线性布局,让每个子视图使用大小相同的屏幕空间,
然后,请将每个视图的 android:layout_weight 设置为 “1”。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}"
android:orientation="horizontal"
>
<Button
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:background="#ff0000"
/>
<Button
android:layout_weight="4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:background="#00ff00"
/>
<Button
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:background="#ffff00"
/>
</LinearLayout>
效果:
4.divider分割线
- divider—为LinearLayout设置分割线图片
- showDividers—设置分割线所在位置,四个值,none.middle,begining,end
- dividerPadding—设置分割线的padding
4.id属性
引用id:@id
设置id:@+id
java文件找id:findViewById