How would I display one view as an overlay of another?

ace picture ace · Feb 4, 2011 · Viewed 56.6k times · Source

I have two views that take the whole screen and I want to display both views at the same time, one on top of the other. My layout looks like this:

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

Note that myCustomView uses onDraw (this method last statement is invalidate()) to draw custom graphics. The problem I am getting is that it only displays myCustomView, WebView is hidden. I tried to change the background colour of mycustomView to transparent but this makes no difference.

I would also like to have the ability to make myCustomView as an overlay on WebView or vice versa.

Answer

techiServices picture techiServices · Feb 4, 2011

Use a RelativeLayout for starters.

You could use the ViewGroup.addView(View child, int index, ViewGroup.LayoutParams params) or a variant along with ViewGroup.removeView(View view) or ViewGroup.removeViewAt(int index).

This would obviously require you to inflate the views manually using LayoutInflater but you could keep a global reference to each after inflating and just flip between the two.