Sunday, July 11, 2010

Custom ContextMenu using PopupWindow Sample

Here we are creating a  custom contextmenu using PopupWindow in android. A simple PopUpWindow can be created using the following steps.
   1)A layout XML  which describes the View that will be rendered within a PopUpWindow  has to be created.
   2)Invoke the PopUpWindow by inflating the layout XML,  and assign appropriate  “parent view”  to  the pop-up.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:orientation="vertical" android:padding="10dip" android:layout_width="fill_parent"
android:layout_height="wrap_content" >
    <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_marginTop="10dip" android:text="Test Pop-Up"/>

Java Code:
    LayoutInflater inflater = (LayoutInflater)
    PopupWindow pw = new PopupWindow(
    inflater.inflate(R.layout.popup_example, null, false),  100,  100,    true);
    // The code below assumes that the root container has an id called 'main'
    pw.showAtLocation(this.findViewById(, Gravity.CENTER, 0, 0); 

How to Dismiss the PopUp Window?

Declare the necessary variables:

         private PopupWindow Popup;
       //how much time your popup window should appear
        private static final int POPUP_DISMISS_DELAY = 4000
       private DismissPopup mDismissPopup = new DismissPopup();

Class for dismissing the PopUp Window
Create a class which helps in dismissing the window automatically after the specified time:
class DismissPopup implements Runnable {
  public void run() {
      // Protect against null-pointer exceptions
      if (mPopup != null) {

Code Snippet:
Popup = new PopupWindow(this.getViewInflate()
Popup.setTouchInterceptor(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
return false;

Popup.showAtLocation(this.findViewById(,Gravity.BOTTOM, 20, 20);

youractivity.postDelayed(mDismissPopup, POPUP_DISMISS_DELAY)


  1. Any chance you could include a sample image of the resulting popup?

    Additionally, include a downloadable sourcecode project.


  2. Nice, like this there is site where they are providing the source code itself

  3. Check out my Windows Phone 7 User Interface to see this implemented a bit more dynamic. You can override Activity callbacks like onOptionsMenuSelected and use a custom context menu a bit easier. (Donate Market version) (XDA Forum)

  4. This comment has been removed by the author.