How to draw a view on top of everything?

后端 未结 5 1198
独厮守ぢ
独厮守ぢ 2020-12-04 14:16

I want to make an app that can create notification on the screen on top of anything that is currently being displayed. Something like the Go SMS message popup or something l

5条回答
  •  Happy的楠姐
    2020-12-04 14:19

    Here is how things like Toast and dialog windows work:

    In the case where just adding or bringing to front does not work, say when you are having a service add its own view to another client activity or application (FaceUnlock does this), or you cannot depend on hierarchies, you need to use the window manager and a window token to do the trick. You can then create layouts and take advantage of animations and hardware acceleration as before.

        WindowManager windowManager = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);
    
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.FIRST_SUB_WINDOW);
        layoutParams.width = 300;
        layoutParams.height = 300;
    
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.flags =
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                        | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
        layoutParams.token = getWindow().getDecorView().getRootView().getWindowToken();
    
        //Feel free to inflate here
        mTestView = new View(this);
        mTestView.setBackgroundColor(Color.RED);
    
        //Must wire up back button, otherwise it's not sent to our activity
        mTestView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    onBackPressed();
                }
                return true;
            }
        });
        windowManager.addView(mTestView, layoutParams);
    

    Then be sure to remove the view onDestroy (or onPause) or you will crash

       if (mTestView != null) {
           WindowManager windowManager = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);
           if (mTestView.isShown()) {
                windowManager.removeViewImmediate(mTestView);
           }
       }
    

提交回复
热议问题