【问题标题】:How to enable the home button to return to a common activity?如何让home键回到常用activity?
【发布时间】:2013-09-06 11:50:57
【问题描述】:

我使用ActionbarSherlock 并希望启用主页按钮...
因此,我在基本活动中调用 setHomeButtonEnabled(true)

public class BaseFragmentActivity extends SherlockFragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Sherlock);
        super.onCreate(savedInstanceState);
        getSupportActionBar().setHomeButtonEnabled(true); // Here
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                Intent intent = new Intent(this, HomeActivity.class);
                // startActivity(intent);
                // startActivityIfNeeded(intent, 0);
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

当我使用startActivity(intent)startActivityIfNeeded(intent, 0) 时,HomeActivity 每次都会重新创建(活动会呈现地图并重新创建它很烦人)。

  • 我不想call finish(),因为它只会让我在应用程序层次结构中退一步。相反,我总是想回到HomeActivity
  • 此外,如果可以在 AndroidManifest.xml 中配置该行为会更好,就像在 ActionBar and setDisplayHomeAsUpEnabled() 中描述的那样。
  • 当我返回HomeActivity 时,清除后台堆栈可能也是常识。您对此有何看法?

【问题讨论】:

  • 将你的home Activity设为singleInstance,并且用户startActivity(intent),它将把你旧的home Activity实例放到前面

标签: android android-actionbar actionbarsherlock back-stack android-homebutton


【解决方案1】:

我会考虑对该活动使用单实例启动模式。

AndroidManifest.xml

<activity  android:launchMode="singleInstance">
...
</activity>

Reference

只允许此活动的一个实例一直在运行。这 活动获得一个独特的任务,只有它自己在其中运行;如果是 曾经以相同的意图再次启动,那么该任务将是 提出并调用其 Activity.onNewIntent() 方法。如果这 活动尝试开始一个新活动,该新活动将是 在单独的任务中启动。请参阅任务和回栈文档以了解 有关任务的更多详细信息。

【讨论】:

    【解决方案2】:

    在 Android 文档中,我找到了我要搜索的内容:您可以设置 flag FLAG_ACTIVITY_CLEAR_TOP to clear the back stack。第二个flag FLAG_ACTIVITY_SINGLE_TOP avoid restarting the activity 如果与前面提到的标志结合使用。

    case android.R.id.home: {
        Intent intent = new Intent(this, HomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityIfNeeded(intent, 0);
        return true;
    }
    

    intent 需要使用startActivityIfNeeded() 传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-29
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      相关资源
      最近更新 更多