覆盖Android中的默认后退按钮行为 [英] Overriding default back button behavior in android

查看:78
本文介绍了覆盖Android中的默认后退按钮行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我刚刚学习了如何清除Android中的后台程序.我有两项活动,一项用于登录(LoginActivity),另一项使用该应用程序(MainActivity).它由一堆碎片组成.这是我用来启动MainActivity的代码

I just recently learned how to clear the backstack in Android. I have two activities, one for login (LoginActivity) and one to use the application (MainActivity). It consists of a bunch of fragments. This is the code I used to start the MainActivity

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish(); // call this to finish the current activity

一切正常,当我在MainActivity上并按home按钮时,应用程序关闭.当我备份它时,它将打开MainActivity.但是,当我按下back按钮时,它正在关闭应用程序,当我备份它时,则在打开LoginActivity.如何覆盖back按钮,使其与home按钮相同.

Everything works fine, when I'm on the MainActivity and I press the home button, the application closes. When I open it back up, it opens the MainActivity. But when I press the back button, it's closing the application and when I open it back up, the LoginActivity is opening. How do I override the back button so it behaves the same as the home button.

推荐答案

听起来像您想要覆盖后退按钮的行为,以将应用程序移至后台,而不是执行通常的后退按钮的行为.

Sounds like you want to override the back button behavior to move the app to the background instead of doing the usual back button behavior.

您可以通过覆盖onBackPressed来做到这一点:

You can do this by overriding onBackPressed:

@Override
public void onBackPressed()
{
    moveTaskToBack(true);
}

这篇关于覆盖Android中的默认后退按钮行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆