Android Popup window

This is a simple android program to show a popup window. For this we need two xml files, one for the main window and other for the popup.
The source code for the java file is given below

package com.pack.pop;

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.widget.Button;
import android.widget.PopupWindow;
public class Pop extends Activity
{
/** Called when the activity is first created. */
Button ok;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ok = (Button) findViewById(R.id.but);
ok.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//this is the code for popup window

LayoutInflater inflater = (LayoutInflater) Pop.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Here x is the name of the xml which contains the popup components
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.x,null, false),300,400,true);
//Here y is the id of the root component

pw.showAtLocation(findViewById(R.id.y), Gravity.CENTER, 0,0);
}
});
}
}


The Popup xml file is..

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/poptext"
android:layout_width="225px"
android:layout_height="281px"
android:background="@drawable/pic"
android:text="This is my new PopUp Window "
android:textSize="18sp"
android:textColor="#ff000000"
android:layout_x="53px"
android:layout_y="44px">
</TextView>
<Button
android:id="@+id/widget41"
android:layout_width="234px"
android:layout_height="wrap_content"
android:text="OK"
android:textSize="26sp"
android:typeface="sans"
android:textStyle="bold|italic"
android:layout_x="49px"
android:layout_y="319px"
>
</Button>
</AbsoluteLayout>

Output:

7 comments on “Android Popup window

  • hi, is there a way to create the popup window in onCreate() instead of on button click? I want to use the poppup window as a menu bar at bottom of screen. I was getting a bad window token error when i wrote the code in onCreate();

  • its very difficult to add a popupwindow on oncreate().
    I think you can use a custom AlertDialog window which you can position on the bottom. Also it gives a better feel

    thans

  • @arunkumar: Thanks. that solves it. i still don’t understand why the popup window cannot be created in onCreate().

Comments are closed.