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

ace*_*ace 29 android android-layout android-webview

我有两个视图占据整个屏幕,我想同时显示两个视图,一个在另一个上面.我的布局看起来像这样:

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

    <WebView 
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    />

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

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

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

我也希望有能力myCustomView作为叠加,WebView反之亦然.

tec*_*ces 23

使用a RelativeLayout作为初学者.

您可以使用ViewGroup.addView(View child, int index, ViewGroup.LayoutParams params)或变体连同ViewGroup.removeView(View view)ViewGroup.removeViewAt(int index).

这显然需要您使用手动充气视图,LayoutInflater但是您可以在充气后保持对每个视图的全局引用,并在两者之间进行翻转.

  • 谢谢!我只将LinearLayout更改为RelativeLayout并且工作正常.其他2个答案没有用. (3认同)

Eph*_*aim 15

我不确定你是否可以在同一个xml文件中执行此操作,但我知道如果你移动:

<org.example.myCustomView
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent" />
Run Code Online (Sandbox Code Playgroud)

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

android:theme="@android:style/Theme.Dialog"
Run Code Online (Sandbox Code Playgroud)

完整的陈述应如下所示:

<activity android:name=".name_of_activity"  
    android:label="TextToBeOnTop"  
    android:theme="@android:style/Theme.Dialog">  
</activity>
Run Code Online (Sandbox Code Playgroud)

结果将如下所示(仅适用于您的组件):

在此输入图像描述

虽然当它们仍然在同一个xml文件中时可以做到这一点.如果可能,可以通过单独保留清单并将costomeView编辑为以下内容来完成:

<org.example.myCustomView 
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:theme="@android:style/Theme.Dialog" />
Run Code Online (Sandbox Code Playgroud)

(我将主题语句添加到CustomView中)

如果这不是你想要的东西,那么我会将一些与Nick Campion所说的相似的东西重新贴上,这就是将fillParent改为wrapContent.你可以做到这一点,或者你可以选择你想要的尺寸.这里有两个你可以使用的选项:

<org.example.myCustomView  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="50dip"  
    android:layout_height="50dip" /> 
Run Code Online (Sandbox Code Playgroud)

(你可以将"50dip"更改为你想要的任何数字,只要它以dip结束)

要么:

<org.example.myCustomView  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content" />
Run Code Online (Sandbox Code Playgroud)