Home > Researches, Tutorials > How to create popups in Android

How to create popups in Android

In this post I’ll show you how to create a popup window in Android. A popup window can be used to display an arbitrary view, and it can be very convenient in cases when you want to display an additional information, but don’t want or it’s not appropriate to launch a new activity or  display a dialog.

The final output should look like this:

Android Popup

We will use the PopupWindow class to create the popup.

One thing I would like to mention is that we want the popup to be attached to the button that opened it. For example if the “Show Popup” button from the screenshot above would be positioned in the middle of the screen, we want the popup window stick to the button’s position. To achieve this, first we should get the button’s “x” and “y” position on the screen, and pass them to the popup window. Then will we use an offset to align the popup properly – a bit to the right, and a bit down, so it won’t overlap the whole button.

Another think I would like to mention is that we will use a 9 patch background image for the popup, so it will look more fancy. But of course you can skip it and put any background you want, or no background at all.

9 patch image:

9 patch image

Put the image into res/drawable directory.

 

1. Create a new project in Eclipse:
Project: TestPopup
Activity: TestPopupActivity

2. Open layout/main.xml file and add a button


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#CCC"
android:orientation="vertical" >

<Button
   android:id="@+id/show_popup"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Show Popup" />

</LinearLayout>

3. Create a new layout file: layout/popup_layout.xml that defines the layout of popup.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:id="@+id/popup"
   android:layout_height="wrap_content"
   android:background="@drawable/popup_bg"
   android:orientation="vertical" >

<TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Popup"
   android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
   android:id="@+id/textView2"
   android:layout_marginTop="5dp"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="This is a simple popup" />

<Button
   android:id="@+id/close"
   android:layout_marginTop="10dp"
   android:layout_gravity="center_horizontal"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Close" />

</LinearLayout>

 

4. And now the most interesting part. Open the TestPopupActivity and fill it with below code. Carefully read the comments to understand what's going on.


public class TestPopupActivity extends Activity {

//The "x" and "y" position of the "Show Button" on screen.
Point p;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   Button btn_show = (Button) findViewById(R.id.show_popup);
   btn_show.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View arg0) {

       //Open popup window
       if (p != null)
       showPopup(TestPopupActivity.this, p);
     }
   });
}

// Get the x and y position after the button is draw on screen
// (It's important to note that we can't get the position in the onCreate(),
// because at that stage most probably the view isn't drawn yet, so it will return (0, 0))
@Override
public void onWindowFocusChanged(boolean hasFocus) {

   int[] location = new int[2];
   Button button = (Button) findViewById(R.id.show_popup);

   // Get the x, y location and store it in the location[] array
   // location[0] = x, location[1] = y.
   button.getLocationOnScreen(location);

   //Initialize the Point with x, and y positions
   p = new Point();
   p.x = location[0];
   p.y = location[1];
}

// The method that displays the popup.
private void showPopup(final Activity context, Point p) {
   int popupWidth = 200;
   int popupHeight = 150;

   // Inflate the popup_layout.xml
   LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
   LayoutInflater layoutInflater = (LayoutInflater) context
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

   // Creating the PopupWindow
   final PopupWindow popup = new PopupWindow(context);
   popup.setContentView(layout);
   popup.setWidth(popupWidth);
   popup.setHeight(popupHeight);
   popup.setFocusable(true);

   // Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
   int OFFSET_X = 30;
   int OFFSET_Y = 30;

   // Clear the default translucent background
   popup.setBackgroundDrawable(new BitmapDrawable());

   // Displaying the popup at the specified location, + offsets.
   popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);

   // Getting a reference to Close button, and close the popup when clicked.
   Button close = (Button) layout.findViewById(R.id.close);
   close.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
       popup.dismiss();
     }
   });
}
}
About these ads
  1. May 6, 2012 at 2:32 pm

    Great post again..!

  2. May 7, 2012 at 6:52 pm

    nice tutorial! can you please do a tutorial on sd card, how to work with sd card in AVD, how to read and write file etc thanks!

  3. May 8, 2012 at 9:00 am

    Wooow, nice post … :)
    thank you for tutorial ^_^

  4. May 8, 2012 at 11:34 am

    Nice tutorial. Though I don’t have an Android as of now. It seems something fun to learn. Something similar to iOS too. :)

  5. May 10, 2012 at 9:21 pm

    Nice tutorial, I just picked up a new Android device so I want to try this out.

  6. Chris Arriola
    May 10, 2012 at 11:40 pm

    Wow, great post! I always wondered how Evernote created pop-ups…. Keep it up!

  7. girlunderstandsit
    May 13, 2012 at 9:25 pm

    Hello! Your blog is great. I’m a total beginner in web design, but hope that one day I’ll also write apps for android.
    If you have any ideas what I should start with, please write it on my blog.
    Keep codin’ :D

  8. July 18, 2012 at 5:52 pm

    hello.. i have done to add multiple poppup,.. but i have stack on listview, can you help me? how to add listview inside popup… thanks..

  9. August 14, 2012 at 12:06 am

    nice tutorial Andy , this popup dialog has sooo many uses!!

    a small suggestion . use DIP instead of Pixels for the Width,Height and Offset values

    • August 18, 2012 at 11:34 am

      Hi, thanks for the comments.
      Yep, I agree with you in regards to using DIP instead of Px.

  10. pratham koranne
    August 22, 2012 at 12:38 pm

    Great Post Thanks

  11. venugopal
    October 1, 2012 at 11:46 am

    hi,thanks for giving such explanation please keep on sharing the ideas

  12. October 28, 2012 at 4:40 am

    Great post… Gonna try it out…

  13. Jay
    November 8, 2012 at 11:44 am

    Thanx a bunch..this helped a lot to make a custom menu..

  14. manoj
    November 11, 2012 at 1:59 pm

    Thanx …it help me lot..

  15. Joanne
    November 24, 2012 at 8:25 pm

    hi! have u tried this already using GridView? when an item is clicked the popup will be displayed. your reply will be a great help for me tnx.

    • November 24, 2012 at 9:21 pm

      There isn’t any difference showing the pop-up when a button is clicked, or when an item from GridView is clicked.

      Just call showPopup() in onItemClicked and it should work.

      • Joanne
        November 27, 2012 at 5:57 pm

        hi again! it worked! but how do i access the text view from the popup_layout.xml and set some text when the button is clicked dynamically. i’ve been trying lot of things that may work regarding my question but all of them is giving me an error.. pls help.. thanks in advance…

  16. gokul
    December 7, 2012 at 11:53 am

    hai i when i switched from portrait mode to landscape mode pop up view is disappeared i want retain that popup. please tell me what i need to implement?

  17. December 8, 2012 at 11:26 pm

    Joanne :

    hi again! it worked! but how do i access the text view from the popup_layout.xml and set some text when the button is clicked dynamically. i’ve been trying lot of things that may work regarding my question but all of them is giving me an error.. pls help.. thanks in advance…

    Any controls you want to access from the Popup should be accessed through a reference to the layout of the pop-up.
    This line from the “showPopup()” inflates the layout:

    View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);
    

    Then you would access any controls like TextViews, Buttons through the "layout", ex:

    TextView text = (TextView)layout.findViewById(R.id.textView);
    

    notice, "layout.findViewById()"

  18. Phil Phrank
    December 17, 2012 at 1:50 am

    Thanks. I found this needed some tweaking of margins, and some density-independence calculations to look right. Here’s a way to set the popup size in a general way at the start of showPopup().
    // Convert density independent pixels to pixels
    float density = context.getResources().getDisplayMetrics().density;
    int popupWidth = Math.round(200 * density);
    int popupHeight = Math.round(150 * density);

  19. Mehrosh
    March 8, 2013 at 7:08 am

    Thanks alot dude ….
    Great tutorial worked like a charm in the very first attempt :)

  20. refka
    March 23, 2013 at 11:37 pm

    when i click on show popup ….nothing happens !! why!!!!
    the same code i din’t know why!!

  21. vaidehi
    March 26, 2013 at 12:19 pm

    LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);

    View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

    In eclipse its giving me error,
    In 1st line i.e R.id.popup
    a red line appears on popup and the below error is :-
    (popup cannot be resolved or not a field)

    In 2nd line R.layout.popup_layout
    a red line appears on popup_layout and the below error is :-
    (popup cannot be resolved or not a field)

    please tell me the solution as soon as possible

  22. paramananda
    August 16, 2013 at 1:27 pm

    Many amany thanks! Its realy helpful to me.

  23. Muhammad Aamir Ali
    September 19, 2013 at 5:48 pm

    exellent example thank you so much

  24. daniel
    September 26, 2013 at 3:34 pm

    thanks guy!

  25. vlad
    October 1, 2013 at 2:44 pm

    Helpful post. Thanks for that.
    I am a beginner on the mobile app and your post helped me a lot but i need one more thing:
    let’s keep the presented case: i need the popup to block all the content from the activity( same way as a dialog box, with background color), except the show popup button.
    Basically the popup should have the picture as background but also a background color and fill everything starting below the show popup button.
    Please if you have any ideas on how i could implement this i would appreciate.

  26. January 13, 2014 at 6:46 pm

    I had to rename the 9 patch file after downloading (I assume that is an HTTP server configuration issue) and create the drawable directory, but after that, the project built w/o error. But when I run, I see no text on the Close button, the text, foreground and background of the popup are all out of alignment. Not to mention: the text is very hard to see against the popup background, since they are both shades of grey. On the emulator, (emulating a Nexus 7 but with 8″ screen), I cannot see the difference at all. On the Nook Color HD, I can see the difference, but as I mentioned, everything it out of alignment. Is this sample code making assumptions about screen size/density or about text size?

  27. January 27, 2014 at 2:24 pm

    Hi Veaceslav.
    Thanks a lot for the great, easy to follow tutorial !

    Question : (I haven’t started looking yet, and will do so now, but)
    How would you suggest making the size of popup more dynamic ?
    Maybe doing something like : “Fixed Height with Dynamic width” ?

    • January 27, 2014 at 7:08 pm

      Hi,

      If you need the popup to take as much space as its content takes, then you could specify the window layout mode to WRAP_CONTENT:

      //.....
      popup.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT,
      				ViewGroup.LayoutParams.WRAP_CONTENT);
      

      and remove: popup.setWidth() and popup.setHeight()

  28. Jay
    March 11, 2014 at 12:58 pm

    How to align the popup to the top of a button and not bottom right since my button is in bottom right corner?

  29. May 2, 2014 at 8:46 am

    thank you. this is very useful to me.

  1. January 2, 2013 at 7:10 pm
  2. March 16, 2013 at 10:00 pm
  3. March 31, 2013 at 4:58 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 506 other followers

%d bloggers like this: