我有一个像 Facebook 聊天气泡一样的浮动视图,但与它不同的是,我的叠加层有一个 EditText 并且需要可聚焦。
这是我的浮动视图代码
//Inflate the floating view layout we created
mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_widget_layout, null);
//Add the view to the window.
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
//Specify the view position
params.gravity = Gravity.TOP | Gravity.START; //Initially view will be added to top-left corner
params.x = 0;
params.y = 100;
//Add the view to the window
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView, params);
几乎没问题了,但是有一个问题。当我从service创建覆盖时,系统后退按钮不起作用。如果我使用
FLAG_NOT_FOCUSABLE
系统按钮;主页、最近的内容和返回内容按预期工作。我在 SO 做了一些研究,发现这是一个安全问题,所以我开始寻找替代解决方案,并发现this然后更改了我的代码
// Wrapper for intercepting System/Hardware key events
ViewGroup wrapper = new FrameLayout(this) {
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
Log.v("Back", "Back Key");
return true;
}
return super.dispatchKeyEvent(event);
}
};
//Inflate the floating view layout we created
mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_widget_layout, wrapper);
//Add the view to the window.
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
//Specify the view position
params.gravity = Gravity.TOP | Gravity.START; //Initially view will be added to top-left corner
params.x = 0;
params.y = 100;
//Add the view to the window
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView, params);
现在我可以从浮动视图中获得后按,但如何将此事件(后按)传递到前台应用程序(其他应用程序,不是我的应用程序)?我找到了this,但它对我没有帮助
如果有人可以帮助我或至少提供线索,我将不胜感激
总结
我有一个覆盖视图,它需要可聚焦,但当可聚焦时后退按钮不起作用,我该如何解决这个问题?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
binding.cameraCardView.addOnUnhandledKeyEventListener { _, event ->
if (event.action == KeyEvent.ACTION_UP) {
if (event.keyCode == KeyEvent.KEYCODE_BACK) {
closePage()
}
}
return@addOnUnhandledKeyEventListener true
}
}
本教程似乎有一个解决方案:https://www.geeksforgeeks.org/how-to-make-a-floating-window-application-in-android/
他们最初设置了
FLAG_NOT_FOCUSABLE
,以便覆盖层不会干扰系统后退功能等。他们在 EditText 上设置 onTouch 侦听器,并在此时将标志更新为 FLAG_NOT_TOUCH_MODAL
,以便可以输入文本。