如何以编程方式在android中按下后退按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10718789/
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
How to press back button in android programmatically?
提问by vinothp
In my app I have a logout functionality. If user clicks logout it goes to home screen. Now I am exiting my app by pressing back button. But what I want is I need to exit automatically(i.e Programmatically) as same like as back button functionality. I know by calling finish() will do the functionality. But the thing is it goes to the previous activity.
在我的应用程序中,我有一个注销功能。如果用户单击注销,它会转到主屏幕。现在我按后退按钮退出我的应用程序。但我想要的是我需要像后退按钮功能一样自动退出(即以编程方式)。我知道通过调用 finish() 将完成该功能。但问题是它会转到上一个活动。
回答by Tarun
onBackPressed()
is supported since: API Level 5
onBackPressed()
受支持,因为:API 级别 5
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
onBackPressed();
}
}
@Override
public void onBackPressed() {
//this is only needed if you have specific things
//that you want to do when the user presses the back button.
/* your specific things...*/
super.onBackPressed();
}
回答by josephus
You don't need to override onBackPressed()
- it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed()
whenever you want to "programatically press" the back button.
您不需要覆盖onBackPressed()
- 它已经被定义为当用户按下后退按钮时您的活动将默认执行的操作。因此,onBackPressed()
只要您想“以编程方式按下”后退按钮,就可以随时调用。
That would only result to finish()
being called, though ;)
不过,那只会导致finish()
被调用;)
I think you're confused with what the back button does. By default, it's just a call to finish()
, so it just exits the current activity. If you have something behind that activity, that screen will show.
我认为您对后退按钮的作用感到困惑。默认情况下,它只是对 的调用finish()
,因此它只是退出当前活动。如果您在该活动背后有什么东西,则会显示该屏幕。
What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.
您可以做的是在从登录启动您的活动时,添加一个 CLEAR_TOP 标志,这样当您退出时登录活动将不存在。
回答by Serj Moya
Sometimes is useful to override method onBackPressed() because in case you work with fragments and you're changing between them if you push backbutton they return to the previous fragment.
有时重写方法 onBackPressed() 很有用,因为如果您使用片段并且您在它们之间进行更改,如果您按下后退按钮,它们将返回到前一个片段。
回答by drulabs
Call onBackPressed
after overriding it in your activity.
onBackPressed
在您的活动中覆盖它后调用。
回答by Abhishek Patil
you can simply use onBackPressed();
你可以简单地使用 onBackPressed();
or if you are using fragment you can use getActivity().onBackPressed()
或者,如果您正在使用片段,您可以使用 getActivity().onBackPressed()
回答by dbs ray
Simply add finish(); in your first class' (login activity) onPause(); method. that's all
只需添加完成(); 在你的第一堂课'(登录活动) onPause(); 方法。就这样