Android 线性布局、相对长度等。页边距未按预期工作
组布局中的页边距似乎不起作用 比如说,Android 线性布局、相对长度等。页边距未按预期工作,android,margin,android-linearlayout,Android,Margin,Android Linearlayout,组布局中的页边距似乎不起作用 比如说, <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_margin="40dip" android:layout_width="match_parent" android:layout_height="matc
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="40dip"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="I'm a button" />
</LinearLayout>
应该显示一个按钮,四周有40便士的边距。然而,它的右边和底部都有80便士的利润
我做错什么了吗?
这是虫子吗
一个解决方法是使用重力,但这只适用于均匀的边距
顺便说一句,还有一个类似的问题尚未得到回答。
线性布局上的安卓:padding=“40dp”
,或者按钮上的安卓:layout\u margin=“40dp”将提供您想要的效果。填充定义了视图边缘与其内容之间的空间,布局边距定义了视图侧面的额外空间。问题实际上是FrameLayout
解释边距的方式setContentView()
将您的“主”布局附加到一个FrameLayout
,该布局是视图层次结构的实际根(您可以通过层次结构查看器看到),并由手机提供给您
页边距由父布局管理,因此在本例中,主FrameLayout
。我不知道这是一个特性还是一个bug,但这就是这个布局对边距的解释
好吧,解决方案已经在我打字时发布了:改用填充。如果需要设置版面的边距,只需用另一个线性或相对版面将其包装即可
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:layout_margin="40dip"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="I'm a button" />
</LinearLayout>
</LinearLayout>
用另一个布局包装线性布局是最好的策略。我记得FrameLayout在蜂巢时间段处理边距的方式修复了一些错误,它涉及默认重力设置。这可能确实是一个错误。:)另一种方法是设置android:layout_gravity=“top | left”来查看框架内的布局。这是更好的答案。填充不一定是你想要的,特别是当你的布局有一个可见的背景时。你应该避免仅仅为了给内部布局留出空白而嵌套布局。无论如何,这不是更好的答案。请尝试设置按钮中心水平边距应将LinearLayout
的四周边距设置为40dp
。奇怪的是,它没有按预期工作。