How to deal with key events when adding a view using WindowManager?

I added a custom view with WindowManager, everything is correct. Only one problem: I can’t find where to catch key events such as BACK. I noticed some of the events in the "View.dispatchKeyEvent ()" method in my user view, but not including "BACK" or "HOME". Any advice? Many thanks!

My code looks like this:

// get WindowManager

WindowManager windowManager = (WindowManager) getContext()
  .getSystemService(Context.WINDOW_SERVICE);

// set LayoutParams

WindowManager.LayoutParams wmparams = new WindowManager.LayoutParams(
  WindowManager.LayoutParams.WRAP_CONTENT,
  WindowManager.LayoutParams.WRAP_CONTENT);

wmparams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;

wmparams.format = PixelFormat.TRANSLUCENT;

wmparams.windowAnimations = R.style.fade;

// add this view to screen

windowManager.addView(this, wmparams);

this.setOnKeyListener(new OnKeyListener() {

 @Override
 public boolean onKey(View v, int keyCode, KeyEvent event) {
  // cannot get 'BACK' pressed event here
  return false;
 }
});
+3
source share
2 answers

in your view added to windowmanager, add this

    root.setOnKeyListener(this);
    root.requestFocus();
    root.setFocusable(true);
    root.setFocusableInTouchMode(true);

I tested in windowmanager that it works well

0
source
FrameLayout view = new FrameLayout(getActivity()) {
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            // do you code
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
};

do not set flags:

WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 
0
source

Source: https://habr.com/ru/post/1782434/


All Articles