我正在编写以下代码:
private class HandleBackButton implements OnKeyListener
{
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
if(arg1==KeyEvent.KEYCODE_BACK)
{
showResults(0);
}
return true;
}
}
我对android有点陌生,我的目的是在单击后退按钮时操作上面的代码。用户可以随时单击后退按钮。但是,我如何为 Activity 设置这个监听器呢?我找不到像 this.setOnKeyListener()
这样的东西。
我使用的是 Android 2.3.3。
最佳答案
对于 Activity,您应该覆盖 onBackPressed
,当您按下后退按钮时会调用它。 OnKeyListener
将按键事件分派(dispatch)到 View 。你会发现View类中定义了setOnKeyListener
Interface definition for a callback to be invoked when a hardware key event is dispatched to this view. The callback will be invoked before the key event is given to the view. This is only useful for hardware keyboards; a software input method has no obligation to trigger this listener.
关于java - 处理后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17760565/