Articles‎ > ‎Android Articles‎ > ‎

Popup Layout Window In Android

posted Jan 26, 2011, 10:10 PM by Thiyagaraaj M   [ updated Aug 20, 2011, 4:43 AM ]


Tags: Android,Layout,Popup window,Example Code

Layout

Need two XML Layouts 
One For root Layout (main.xml) and another one for popup window (mydialog.xml)

Root Layout : (main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/ClkBtn"
android:text="Click Me. and Get Dialog"></Button>
</RelativeLayout>

Popup Layout:(mydialog.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:background="#778899"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">
  
 <TextView android:id="@+id/Tv1"
 android:layout_width="fill_parent"
 android:background="#696969"
 android:layout_height="wrap_content"
 android:textSize="20px"
 android:textColor="#FFFFFF"
 android:text="Articles"/>
 
 <TextView android:id="@+id/Tv2"
 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:textSize="14px"
 android:layout_below="@+id/Tv1"
 android:textColor="#FFFFFF"
 android:text="More Android Articles visit\nhttp://i.thiyagaraaj.com"/>
 
 <Button android:id="@+id/Btn1"
 android:layout_below="@+id/Tv2"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:text="Close" />
</RelativeLayout>

Main Activity Java Code:

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;

public class ExPopup extends Activity {
Button myButton;
PopupWindow popupWindow;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        myButton = (Button) findViewById(R.id.ClkBtn);
    
        myButton.setOnClickListener(new OnClickListener() {          
        @Override
            public void onClick(View v) {
         LayoutInflater inflater = (LayoutInflater) ExPopup.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         popupWindow = new PopupWindow(inflater.inflate(R.layout.mydialog,null, false),300,100,true);
// RelativeLayout01 is Main Activity Root Layout
         popupWindow.showAtLocation(findViewById(R.id.RelativeLayout01), Gravity.CENTER, 0,0);
            }
        });
    }
 }

Screenshot: