akdd
akdd

Reputation: 51

How to deal with keyevents when added a view with WindowManager?

I added a custom view with WindowManager, everything is right. Just one problem : I cannot find where to catch keyevents such as 'BACK' pressed. I caught some of the events in method 'View.dispatchKeyEvent()' in my custom view, but not including 'BACK' or 'HOME'. Any Advice? Thanks a lot!

My code is just 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;
 }
});

Upvotes: 3

Views: 3274

Answers (2)

lockup
lockup

Reputation: 11

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 

Upvotes: 0

nguyenvangiangbn
nguyenvangiangbn

Reputation: 161

in your view added into windowmanager, let add this

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

I had tested in windowmanager in service it working well

Upvotes: 1

Related Questions