我如何将一个视图显示为另一个视图的叠加层?

Posted

技术标签:

【中文标题】我如何将一个视图显示为另一个视图的叠加层?【英文标题】:How would I display one view as an overlay of another? 【发布时间】:2011-06-21 13:06:29 【问题描述】:

我有两个视图占据整个屏幕,我想同时显示两个视图,一个在另一个之上。我的布局如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical">

    <WebView 
        android:id="@+id/webview"
        android:layout_
        android:layout_
    />

    <org.example.myCustomView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_
        android:layout_
    />

</LinearLayout>

注意myCustomView使用onDraw(这个方法最后一个语句是invalidate())来绘制自定义图形。我遇到的问题是它只显示myCustomViewWebView 是隐藏的。我尝试将mycustomView 的背景颜色更改为透明,但这没有任何区别。

我还希望能够将myCustomView 叠加在WebView 上,反之亦然。

【问题讨论】:

【参考方案1】:

首先使用RelativeLayout

您可以将ViewGroup.addView(View child, int index, ViewGroup.LayoutParams params) 或变体与ViewGroup.removeView(View view)ViewGroup.removeViewAt(int index) 一起使用。

这显然需要您使用 LayoutInflater 手动扩充视图,但您可以在扩充后保留对每个视图的全局引用,并在两者之间切换。

【讨论】:

谢谢!我只将 LinearLayout 更改为 RelativeLayout 并且它起作用了。其他 2 个答案无效。 FrameLayout 如果您不担心相对于彼此定位事物,那也很好。 Overlay,也就是他的Q,就是FrameLayout 我发现这个 (***.com/a/6690607/2102122) 解决方案更加可靠。关于交叉淡入淡出两个视图 (developer.android.com/training/animation/crossfade.html) 的 google 文档也使用 FrameLayout 将两个视图叠加在一起。【参考方案2】:

我不确定当它们在同一个 xml 文件中时你是否可以这样做,但我知道如果你移动:

<org.example.myCustomView
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_   
    android:layout_ />

到另一个 xml 文件,并创建另一个活动。将内容视图设置为包含 org.example.myCustomView 的 xml 文件并调用该活动。在清单中,当您添加该活动时,添加一个主题声明:

android:theme="@android:style/Theme.Dialog"

完整的语句应该如下所示:

<activity android:name=".name_of_activity"  
    android:label="TextToBeOnTop"  
    android:theme="@android:style/Theme.Dialog">  
</activity>

结果将如下所示(仅与您的组件一起使用):

虽然当它们仍然在同一个 xml 文件中时可能会这样做。如果可能的话,很可能通过不理会清单并将您的 costomeView 编辑为以下内容来完成:

<org.example.myCustomView 
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_  
    android:layout_  
    android:theme="@android:style/Theme.Dialog" />

(我在 CustomView 中添加了主题声明)

如果这不是您想要的,那么我会推荐与 Nick Campion 所说的类似的东西,即将 fillParent 更改为 wrapContent。 你可以这样做,或者你可以选择你想要的尺寸。您可以使用以下两个选项:

<org.example.myCustomView  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_  
    android:layout_ /> 

(您可以将“50dip”更改为您想要的任何数字,只要它以 dip 结尾)

或:

<org.example.myCustomView  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_  
    android:layout_ />

【讨论】:

【参考方案3】:

术语fill_parent 表示消耗父级中所有允许的空间。尝试将其设置为wrap_content。然后你可以尝试将weight = 1添加到两者中,以尝试平均分配剩余空间。

【讨论】:

以上是关于我如何将一个视图显示为另一个视图的叠加层?的主要内容,如果未能解决你的问题,请参考以下文章

AE中如何将一个图层设置为另一个图层的遮罩层

可以使用 MapKit 在地图上添加叠加层吗?

Swiftui-仅显示视图的百分比

Android 在一切之上叠加一个视图?

在相机视图中保存带有叠加层的图像

我们如何将一个 UIView 设置为另一个 UIView 的掩码