Android Studio 视图对齐方式
这里有两种类型的对齐
1、layout_gravity
用于当前视图相对于上级视图的对齐方式
2、gravity
用于下级视图相对于当前视图的对齐方式
具体如下代码和图
copy
<?xml version="1.0" encoding="utf-8"?> <!--最外层的布局背景为蓝色 --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="300dp" android:background="#ffff99" android:orientation="horizontal"> <!-- 第一个子布局背景为红色,它在上级视图中朝下对齐,它的下级视图则靠左对齐 --> <LinearLayout android:layout_width="0dp" android:layout_height="200dp" android:layout_margin="10dp" android:layout_weight="1" android:background="#ff0000" android:padding="10dp" android:layout_gravity="bottom" android:gravity="left" > <View android:layout_width="100dp" android:layout_height="100dp" android:background="#00ffff" /> </LinearLayout> <!--第二个子布局背景为红色,它在上级视图中朝上对其,它的下级视图则靠右对齐 --> <LinearLayout android:layout_width="0dp" android:layout_height="200dp" android:layout_gravity="top" android:layout_weight="1" android:layout_margin="10dp" android:padding="10dp" android:background="#ff0000" android:gravity="right"> <View android:layout_width="100dp" android:layout_height="100dp" android:background="#00ffff"/> </LinearLayout> </LinearLayout>
在LinearLayout中对layout_gravity和gravity属性进行设置即可
简单点说就是 Layout_gravity是调整红色和黄色部分之间的位置
而gravity是调整蓝色部分和红色部分之间的位置关系
有left、top、right、bottom等
当然也可以用竖线连接各取值,例如 left|top表示朝左上角对齐
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步