Android之android:gravity和android:layout_gravity属性

转自: http://blog.youkuaiyun.com/salc3k/article/details/6683279



Android 开发中,使用 `android:layout_gravity` 实现底部居中的方法会因布局类型不同而有所差异。 ### 在 LinearLayout 中实现底部居中 当使用 `LinearLayout` 布局时,需根据 `android:orientation` 的值来设置 `android:layout_gravity`。若 `android:orientation="vertical"`,可使用 `android:layout_gravity="bottom|center_horizontal"` 实现底部居中。示例代码如下: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|center_horizontal" android:text="Button" /> </LinearLayout> ``` ### 在 FrameLayout 中实现底部居中 在 `FrameLayout` 里,可直接使用 `android:layout_gravity="bottom|center_horizontal"` 让视图底部居中。示例代码如下: ```xml <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|center_horizontal" android:text="Button" /> </FrameLayout> ``` ### 注意事项 在 `RelativeLayout` 中,`android:layout_gravity` 无法直接用于控制视图的对齐方式,`android:layout_gravity` 在 `RelativeLayout` 里不起作用。若要在 `RelativeLayout` 中实现底部居中,需使用 `RelativeLayout` 特有的属性,如 `android:alignParentBottom="true"` `android:centerHorizontal="true"`。示例代码如下: ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Button" /> </RelativeLayout> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值