10

是否可以将元素浮动到 Android 中的其他元素之上,这样它们就不会影响其容器的布局?

我想要达到的效果是一个浮动的类似气泡的元素:

在此处输入图像描述

上面的黄色框是我想要漂浮在其他元素之上的元素,但正如您所见,它会将其容器向下推,在绿色条下方创建黑色空间,而不是漂浮在其下方的灰色区域上方。

RelativeLayout 可以适当地定位元素,但我找不到使定位的元素不扩展其容器边界的方法。这在Android上甚至可能吗?


类比

  • 在网络世界中,等价物是具有“位置:绝对”的元素,因此不被视为“流”的一部分(即:布局)
  • 在 WPF 世界中,等效的元素是位于 Canvas 内的元素。Canvas 有自己的边界,它占用布局中的空间,但它的子元素可以位于其边界之外并且不会影响布局
  • 在 iOS 世界中,每个视图都被定位为画布(因为没有布局管理器),所以这种行为是通过简单地偏移元素框架的 x 和 y 属性来实现的
4

2 回答 2

14

RelativeLayout 可以适当地定位元素,但我找不到使定位的元素不扩展其容器边界的方法。

那么你有错误的容器。

例如:

<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>

浮动按钮

在这里,小按钮漂浮在大按钮之上。小按钮并没有“扩展其容器的边界”,仅仅是因为容器是整个内容视图。

您将RelativeLayout(或FrameLayout)容器设置为包含您的孩子可以漂浮的可能区域的容器。无论是整个屏幕还是只是一个子集都取决于您。反之,如果你的孩子影响了其容器的边界,则说明你使用了错误的容器,或者需要专门为这个角色设置一个容器。

在另一个例子中,Roman Nurik 展示了如何实现一个浮动的“撤消栏”,类似于 Gmail 的:

浮动撤消栏

于 2012-09-25T23:03:15.147 回答
2

看看 android 中的相对布局:例如,当您没有在相对布局中的所有视图上指定位置时,它们将浮动在彼此之上。

http://developer.android.com/guide/topics/ui/layout/relative.html

例子:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="#444444"
        android:text="Update"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <TextView
        android:id="@+id/lost_of_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/some_button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="text view with lots of text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/some_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Some Button" />

</RelativeLayout>

编辑:CommonsWare 更快;)看看他漂亮的答案!

于 2012-09-25T23:05:17.673 回答