Android Actionbar Up按钮与系统后退按钮

mra*_*tor 30 android android-actionbar

我正在使用Actionbar和它的"向上"按钮从详细活动返回到主要活动,这很好.类似地,用户可以按下系统"后退"按钮返回主活动.

在我的主要活动中,onCreate()数据从互联网下载,以便在应用程序启动时显示.我注意到当我使用Actionbar"向上"按钮从详细信息转到主要活动时,onCreate()运行,重新下载数据.但是onCreate()当我使用系统"后退"按钮时不运行,因此立即显示主要活动视图.

我在详细活动中用来实现"向上"按钮的代码是:

switch (item.getItemId()) {
   case android.R.id.home:
      Intent intent = new Intent(this, MainActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
      return true;
Run Code Online (Sandbox Code Playgroud)

我希望"向上"按钮的行为类似于"后退"按钮,而不是重新运行onCreate().但我不确定如何实现这一点,或者"后退"按钮实现返回主活动的代码路径.

谢谢!

dym*_*meh 49

而不是开始一个全新的活动,只需完成您所在的详细活动

switch (item.getItemId()) {
   case android.R.id.home:
      finish();
      return true;
Run Code Online (Sandbox Code Playgroud)

然后,您将返回活动堆栈上的上一个活动(您的主要活动),并且不应该调用onCreate

  • 这不是**永远是正确的解决方案.有时活动从另一个应用程序开始,`up`应该启动父活动.更多关于它的信息:http://developer.android.com/training/implementing-navigation/ancestral.html (13认同)
  • 是的,但是在google解决方案中,`onCreate`甚至在堆栈中的活动时调用,你知道如何在活动已经存在时使用模仿'后退'功能,否则创建一个? (4认同)
  • @shem知道它的晚期(可能会帮助某一天,有一天)在你的parentActivity上使用`android:launchMode ="singleTop"`! (4认同)

Kri*_*son 10

如果你想要完全按照Back做的话,你可以这样做:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)

请注意,onBackPressed()只是调用的默认实现finish(),但onBackPressed可以重写.


the*_*11s 8

我认为在这篇文章中可以找到更好的解决方案.

调用finish()在特定情况下工作,但可能并不总是产生文档中描述的行为,例如:

在此输入图像描述

通过电话

Intent intent = NavUtils.getParentActivityIntent(this); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP); 
NavUtils.navigateUpTo(this, intent);
Run Code Online (Sandbox Code Playgroud)

您将返回到您离开状态的父活动.如果你有一个扁平的应用程序结构,它仍然会像后退按钮一样.

  • 这与在清单中设置`singleTop`只是以编程方式相同.好答案 (2认同)