是否可以在 Android 中将元素 float 到其他元素之上,以便它们不影响其容器的布局?
我要实现的效果是一个漂浮的泡泡状元素:
上面的黄色框是我想要 float 在其他元素上方的元素,但正如您所见,它会将其容器向下推,在绿色条下方创建黑色空间,而不是 float 在其下方的灰色区域上方。
RelativeLayout 可以适当定位元素,但我找不到使定位元素不扩展其容器边界的方法。这甚至可以在 Android 上实现吗?
类比
- 在网络世界中,等效元素是具有“position: absolute”的元素,因此不计入“流”(即:布局)的一部分
- 在 WPF 世界中,等效项是位于 Canvas 中的元素。 Canvas 有自己的边界,在布局中占用空间,但它的子元素可以位于其边界之外,不会影响布局
- 在 iOS 世界中,每个 View 都定位为 Canvas (因为没有布局管理器),所以这种行为是通过简单地偏移元素框架的 x 和 y 属性来实现的
最佳答案
RelativeLayout can position the element appropriately but I cannot find a way to make the positioned element not expand the boundary of its container.
那么你用错了容器。
例如:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/big"
android:textSize="120dip"
android:textStyle="bold"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/small"/>
</RelativeLayout>
在这里,小按钮漂浮在大按钮上方。小按钮不会“扩展其容器的边界”,只是因为容器是整个内容 View 。
您将 RelativeLayout
(或 FrameLayout
)容器设置为包含您的 child 可以漂浮的可能区域的容器。是整个屏幕还是只是一个子集由您决定。相反,如果您的 child 正在影响其容器的边界,则说明您使用了错误的容器,或者需要专门为此角色设置一个容器。
在另一个例子中,Roman Nurik shows how to implement a floating "undo bar" ,类似于 Gmail 的:
关于android - float View ,这样它们就不会占用布局中的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12592291/