TabActivities 中的关键事件?
我有一个 TabActivity,想要捕获并处理 HOME 和 BACK 的按下。我需要在哪里捕捉这些事件?
在我的 TabActivity 子类中,我实现了以下内容:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
// Code handling
}
return super.onKeyDown(keyCode, event);
}
不起作用。
所以我在 switch 语句行上放置了一个断点。但无论我按音量增大/减小、菜单、主页还是返回,此函数都永远不会被调用。我需要在哪里捕获这些关键事件?
I have a TabActivity and want to catch and handle presses of HOME and BACK. Where do I need to catch these events?
In my subclass of TabActivity I implement the following:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
// Code handling
}
return super.onKeyDown(keyCode, event);
}
Didn't work.
So I placed a breakpoint on the switch statement line. But this function never gets called, whether I press volume up/down, menu, home, or back. Where do I need to catch these KeyEvents?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
事实证明这很容易。将以下代码添加到您的子选项卡活动中:
然后在 TabActivity 中执行真正的逻辑:
否则,子项将拦截并使用该事件而不通知选项卡主机。
It turns out to be pretty easy. Add the following code to your child tab activity :
Then in the TabActivity do the real logic:
Otherwise, the children will intercept and consume the event without notifying the tab host.
我遇到了同样的问题,发现重写dispatchKeyEvent 有效。
可以在此处找到按后退按钮的示例:
http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys- Three-stories.html
I had the same issue and found overriding dispatchKeyEvent worked.
An example of which can be found here for back button press:
http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
每个选项卡的活动处理“后退”按下。
Each tab's Activity handled the "back" presses.
你永远无法“处理回家的新闻”。
对于 BACK,您可以使用
onKeyDown()
(适用于 Android 1.x)或onBackPressed()
(适用于 Android 2.x)。但是,您的TabActivity
可能为时已晚。例如,如果您将活动作为选项卡的内容,则其中之一可能正在捕获 BACK 按键并安排正常处理(即关闭活动)。由于我避免像瘟疫一样将活动作为选项卡(除了一本书的示例),因此我没有在这种情况下尝试过“后退”按钮处理。You cannot "handle presses of HOME", ever.
With respect to BACK, you can use
onKeyDown()
(for Android 1.x) oronBackPressed()
(for Android 2.x). However, yourTabActivity
may be too late. For example, if you have activities as the contents of your tabs, it may be that one of them is catching the BACK press and arranging for normal processing (i.e., closing up of the activity). Since I avoid activities-as-tabs like the plague (except for one book example), I have not experimented with BACK button processing in that scenario.在您的
oncreate()
中尝试一下try this in your
oncreate()