android 中是否有默认的后退键(在设备上)侦听器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2592037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is there a default back key(on device) listener in android?
提问by Praveen
I am having two activities A and B. when i click the button in A that will shows B. when i click the Button in B it backs to A. i had set the overridePendingTransition method after the finish() method. it works properly. but in case the current Activity is B. on that time i click the default back button in the device. it shows the right to left transition to show the Activity A.
我有两个活动 A 和 B。当我单击 A 中将显示 B 的按钮时。当我单击 B 中的按钮时,它返回到 A。我在 finish() 方法之后设置了 overridePendingTransition 方法。它工作正常。但如果当前活动是 B。那时我单击设备中的默认后退按钮。它显示了从右到左的过渡以显示活动 A。
How i can listen that Default back key on device?
我如何在设备上收听默认后退键?
EDIT:
编辑:
Log.v(TAG, "back pressed");
finish();
overridePendingTransition(R.anim.slide_top_to_bottom, R.anim.hold);
回答by Jamie Keeling
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
The following link is a detailed explanation on how to handle back key events, written by the Android developers themselves:
以下链接是Android开发者自己编写的关于如何处理返回键事件的详细说明:
回答by Nikolay Ivanov
For Android 2.0 and later, there is a specific method in the Activity class:
对于Android 2.0及更高版本,Activity类中有一个特定的方法:
@Override
public void onBackPressed() {
super.onBackPressed();
// Do extra stuff here
}
回答by YaW
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
//Do stuff
}
return super.onKeyDown(keyCode, event);
}
回答by Moss
More info on back key stuff can be found here: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
更多关于后退键的信息可以在这里找到:http: //android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
回答by NickOpris
I use this code on an activity with a media player. I needed to stop the playback when user pressed the back button but still be able to go back to previous activity.
我在带有媒体播放器的活动中使用此代码。当用户按下后退按钮时,我需要停止播放,但仍然能够返回到之前的活动。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
try{
mp.stop(); //this line stops the player
return super.onKeyDown(keyCode, event);//this line does the rest
}
catch(IllegalStateException e){
e.printStackTrace();
}
return true;
}
return super.onKeyDown(keyCode, event); //handles other keys
}