我用 WindowManager 添加了自定义 View ,一切正常。 只有一个问题:我找不到在哪里可以捕捉按键事件,例如按下“BACK”。 我在自定义 View 中捕获了方法“View.dispatchKeyEvent()”中的一些事件,但不包括“BACK”或“HOME”。 有什么建议吗? 非常感谢!
我的代码是这样的:
// 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;
}
});
最佳答案
在你添加到windowmanager的 View 中,让我们添加这个
root.setOnKeyListener(this);
root.requestFocus();
root.setFocusable(true);
root.setFocusableInTouchMode(true);
我已经在 windowmanager 服务中测试过它运行良好
关于android - 使用WindowManager添加 View 时如何处理按键事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4545623/