Android PopupWindow

Android PopupWindow are useful if you need to assign a specific size and position to it. If you don’t, then I would suggest using Dialog instead.

First you have to define a layout for your popup window. Like this simple one (popup_menu.xml):

<?xml version="1.0" encoding="utf-8"?>

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

	<Button
		android:layout_height="wrap_content"
		android:layout_width="wrap_content"
		android:text="Button"
		android:id="@+id/button">
	</Button>

</LinearLayout>

Then, you create a class which will handle you PopupWindow :

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.PopupWindow;

public class PopupMenu extends PopupWindow
{
	Context		m_context;

    public PopupMenu(Context context)
    {
        super(context);

        m_context = context;

        setContentView(LayoutInflater.from(context).
             inflate(R.layout.popup_menu, null));

        setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
    }

    public void show(View anchor)
    {
        showAtLocation(anchor, Gravity.CENTER, 0, 0);
    }
}

By default, a PopupWindow has a size of 0x0, that’s why we have to set a width and height. If you don’t, your PopupWindow won’t be visible.

The showAtLocation method lets you set the position of your window. It can be set according to an existing View which can be useful if you want to use the PopupWindow as a contextual menu.

Then we just have to display our popup window :

PopupMenu popupMenu = new PopupMenu(context);
popupMenu.show(view);

This code should be placed when the user is trigerring an event, like clicking on a button.

The context variable, is your current context, which is usually an Activity.
The view variable, is the anchor (parent) view of your popup window.

If you put a listview in your PopupWindow, setting the width to WRAP_CONTENT won’t work. In order to the set PopupWindow width properly, you’ll have to add this in the show() method :

// force the popupwindow width to be the listview width
listview.measure(
                 View.MeasureSpec.UNSPECIFIED,
                 View.MeasureSpec.UNSPECIFIED)
setWidth(listview.getMeasuredWidth());

 

Full PopupWindow documentation

1 thought on “Android PopupWindow

Leave a comment