Reputation: 23025
I am working on the following code:
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;
}
}
I am somewhat new to android and my purpose is to operate the above code when the back button is clicked. User can click the back button any time. But, how can I set this listener to the Activity? I can't find something like this.setOnKeyListener()
.
I am using Android 2.3.3.
Upvotes: 0
Views: 954
Reputation: 3735
You can use onBackPressed()
:
@Override
public void onBackPressed() {
showResults(0);
}
Upvotes: 1
Reputation: 5673
Just override the onKeyDown()
method of Activity.
You don't have to set a listener then.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
showResults(0);
return true;
}
return super.onKeyDown(keyCode, event);
}
Optionally you can also override onBackPressed()
if your api level is >= 5.
Upvotes: 2
Reputation: 157457
For the Activity you should override onBackPressed
which is invoked when you press the back button. OnKeyListener
dispatches key events to the view. You find setOnKeyListener defined in the View class
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.
Upvotes: 3