Search code examples
androidpopupwindowscreencenter

Popup Window shows at the center of the screen and outside of the context


What I want is... there's a floating icon (always on top of other apps). Tapping it wil show a popup window which is on the center of the screen. I have tried the accepted answer here but it didn't work :(


Solution

  • Okay, after wrestling with it, I found a way to do this. It's kinda tricky LOL.

        public void createWindow() {
        //initialize the popup window
        // blah blah blah and right before you're about to show it, create
        // a framelayout like the one below. And use windowmanager to addView 
        // (just like the way we create a floating icon on top of other apps)
        framelayout = new FrameLayout(this);
        WindowManager.LayoutParams layoutparameters = new WindowManager.LayoutParams(
                width, height, WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);
    
        parameters.gravity = Gravity.TOP | Gravity.LEFT;
        manager.addView(framelayout, layoutparameters);
        framelayout.post(new Runnable() {
            public void run() {
                pop.showAtLocation(framelayout, Gravity.CENTER, 0, 0);
            }
        });
        }
    

    Not done yet, my friends! Don't forget this in the method createWindow().

        pop.setOnDismissListener(new OnDismissListener() {
    
            @Override
            public void onDismiss() {
                new Handler().postDelayed(new Runnable() {
    
                    @Override
                    public void run() {
                        try {
                            manager.removeView(framelayout);
                            framelayout = null;
                        } catch (Exception e) {
    
                        }
                    }
                }, 500);
    

    You can leave the handler. I use it because my popup window uses animation to dismiss (and yes my animation duration is 500 mili). Done!