Android开发:如何设置Button与其边界的间距?
要给Button和父布局边界设置间距,核心使用margin系列布局属性,具体选项如下:
android:layout_margin:一次性统一设置上下左右四个方向的间距android:layout_marginTop/android:layout_marginBottom:单独设置顶部/底部间距android:layout_marginStart/android:layout_marginEnd:单独设置起始侧/结束侧间距(适配不同语言的布局方向,推荐优先使用)android:layout_marginLeft/android:layout_marginRight:单独设置左/右侧间距
以下是修改后的布局代码示例,给Button添加统一的四边间距:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/false_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="hello" android:textSize="50sp" android:layout_margin="20dp"/> <!-- 统一四边间距为20dp --> </FrameLayout>
如果需要自定义不同方向的间距,比如只设置左右和顶部:
<Button android:id="@+id/false_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="hello" android:textSize="50sp" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:layout_marginTop="24dp"/>
注意:推荐使用dp作为尺寸单位,它能自动适配不同分辨率的Android设备。
内容的提问来源于stack exchange,提问作者VanechikSpace
相关产品推荐
相关产品推荐

