gpt4 book ai didi

android - 我可以在自定义 ViewGroup 中获取 onBackPressed 事件吗?

转载 作者:太空狗 更新时间:2023-10-29 15:39:03 28 4
gpt4 key购买 nike

我正在创建一个自定义 Android 组件,它有时需要使用 onBackPressed 事件(例如,自定义 ViewGroup 中有一个弹出菜单,如果它正在显示,后退按钮事件将其关闭并被使用,否则将被忽略)。那可能吗?我可以从我的 ViewGroup 子类中拦截此事件吗?如何拦截?

编辑:正如 Android 文档所暗示的那样,我尝试覆盖 onKeyPreIme,该方法从不从 ViewGroup 中调用。

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event)
{
return true;
}

onKeyPreIme 文档中说:

Handle a key event before it is processed by any input method associated with the view hierarchy. This can be used to intercept key events in special situations before the IME consumes them; a typical example would be handling the BACK key to update the application's UI instead of allowing the IME to see it and close itself.

最佳答案

永远不会调用 onKeyDown 或 onKeyPreIme 的原因是因为 ViewGroup 没有焦点。

解决方案是在 ViewGroup 子类的构造函数中请求焦点:

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

关于android - 我可以在自定义 ViewGroup 中获取 onBackPressed 事件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11931080/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com