Thursday 7 October 2010

Android: creating pop-up menus at specific screen locations

If you need to create a pop-up menu in Android, anchored to a specific View on the screen you could use this simple code as a template:
http://www.londatiga.net/it/how-to-create-quickaction-dialog-in-android/

However, what if you want your pop-up to appear at a particular position on screen, where you don't have a View to anchor to (maybe to overlay some other element on-screen that you don't have ownership of)?

My solution was as follows:
- Create a new Linear Layout to use as a "canvas" - call it my_canvas - and set to fill parent.
- Create a single ImageView (with empty drawable - it'll remain invisible!) within that layout, set to wrap content; call it my_canvas_image.
- We then create dynamically a view based on the layout, with left and right margin properties to pixel-position to the correct place on screen; use the image in that view as the anchor for our pop-up; and remove the view when done.

When your activity is created, grab the ViewGroup used to create the main activity layout like this:

    LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ViewGroup appViewGroup = (ViewGroup) inflater.inflate(R.layout.myApp, null);
    setContentView(appView);

When you need to create the pop-up at a given screen location, you can use code like this:


    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    int screenWidth = windowManager.getDefaultDisplay().getWidth();
    int screenHeight = windowManager.getDefaultDisplay().getHeight();
   
    LinearLayout.LayoutParams paramsx = new LinearLayout.LayoutParams(screenWidth, screenHeight);
    paramsx.leftMargin = putPopUpHereX;
    paramsx.topMargin = putPopUpHereY;
       
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View canvasView = inflater.inflate(R.layout.my_canvas, null);
   
    appViewGroup.addView(canvasView);

    ImageView imageViewUseAsAnchor = (ImageView) canvasView.findViewById(R.id.my_canvas_image);
   
... the imageViewUseAsAnchor item can then be used as the "anchor" to which to attach the pop-up menu at your required screen location!

When you've finished, you can then remove the "canvas" view with:

    appViewGroup.removeView(canvasView);