Android: addview()- adding a new view on top of activity

android, android-activity, android-layout

I have the following layout with an imageview and textfield,

<?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"    android:orientation="vertical"     >    <ImageView        android:id="@+id/imageView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_alignParentTop="true"        android:layout_marginRight="26dp"        android:layout_marginTop="22dp"        android:src="@drawable/a01" />     <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_below="@+id/imageView1"        android:layout_marginTop="31dp"        /></RelativeLayout>

This layout will be transparent and I want to call this layout on top of a particular activity ,when the particular activity first starts, how to implement it with addview()?

Best Solution

When you want to show it:

FrameLayout rootLayout = (FrameLayout)findViewById(android.R.id.content);View.inflate(this, R.layout.overlay_layout, rootLayout);

Then when you want to remove it:

FrameLayout rootLayout = (FrameLayout)findViewById(android.R.id.content);rootLayout.removeViewAt(rootLayout.getChildCount()-1);

That's a concise solution, you should remove the View by giving the RelativeLayout an id in the XML file, then remove by: rootLayout.removeView(findViewById(R.id.the_id_of_the_relative_layout));.