LinearLayout通过属性android:orientation区分两种方向,其中从左到右排列叫作水平方向,属性值为horizontal;从上到下排列叫作垂直方向,属性值为vertical。如果LinearLayout标签不指定具体方向,则系统默认该布局为水平方向排列,也就是默认android:orientation="horizontal"。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="横排第一个" android:textSize="17sp" android:textColor="#000000" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="横排第二个" android:textSize="17sp" android:textColor="#000000" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="竖排第一个" android:textSize="17sp" android:textColor="#000000" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="竖排第二个" android:textSize="17sp" android:textColor="#000000" /> </LinearLayout> </LinearLayout>
效果:
除了方向之外,线性布局还有一个权重概念,通过属性android:layout_weight来表达。
假设线性布局平均分为左右两块,则甲视图和乙视图的权重比为1:1,意味着两个下级视图的layout_weight属性都是1。一旦设置了layout_weight属性值,便要求layout_width填0dp或者layout_height填0dp。如果layout_width填0dp,则layout_weight表示水平方向的权重,下级视图会从左往右分割线性布局;如果layout_height填0dp,则layout_weight表示垂直方向的权重,下级视图会从上往下分割线性布局。 按照左右均分的话,线性布局设置水平方向horizontal,且甲乙两视图的layout_width都填0dp,layout_weight都填1
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="横排第一个" android:textSize="17sp" android:textColor="#000000" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="横排第二个" android:textSize="17sp" android:textColor="#000000" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:text="竖排第一个" android:textSize="17sp" android:textColor="#000000" /> <TextView android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:text="竖排第二个" android:textSize="17sp" android:textColor="#000000" /> </LinearLayout>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!