【问题标题】:How do I pass variables between activities in Android?如何在 Android 中的活动之间传递变量?
【发布时间】:2018-09-21 13:20:52
【问题描述】:

假设我的应用程序具有“提交后”功能。有两种活动和布局:

  1. 主要帖子活动
  2. 位置选择活动

当它们已经打开时,如何在它们之间传递变量?我已经知道它们没有打开时的情况。我使用“singleTask”模式来防止多个实例。

我需要这个的原因是有一个按钮链接到 MainPostActivity 上的 LocationSelectionActivity。我希望当有人单击按钮时,选择位置,然后返回 MainPostActivity 而不重新启动任何活动,这样填充的字段就不会重置。

【问题讨论】:

标签: android


【解决方案1】:

onActivityResult()startActivityForResult() 一起使用。

参考:https://developer.android.com/training/basics/intents/result

【讨论】:

    【解决方案2】:

    您可能正在寻找onNewIntent,您可以在您的Activity 类中覆盖它并在您的onResume 方法中检索新的Intent。

        /**
         * Override super.onNewIntent() so that calls to getIntent() will return the
         * latest intent that was used to start this Activity rather than the first
         * intent.
         */
        @Override
        public void onNewIntent(Intent intent){
            super.onNewIntent(intent); // Propagate.
            setIntent(intent); // Passing the new intent to setIntent() means this new intent will be the one returned whenever getIntent() is called.
        }
    

    【讨论】:

      【解决方案3】:

      您不应该为此使用活动,您处于自己的“主流程”中,因此您应该为此使用 1 个活动和 2 个片段。

      然后你可以在MainPostFragment 中使用locationSelectionFragment.setTargetFragment(this); 在它被添加到Activity 的片段事务之前,这样你就可以使用getTargetFragment() 来传回值:

      ((MainPostFragment)getTargetFragment()).giveValueBack(value);
      

      但还有其他多种选择,每个都有自己的优点和缺点as described in this article

      【讨论】:

        猜你喜欢
        • 2011-10-06
        • 2017-10-10
        • 2013-08-01
        • 1970-01-01
        • 2013-02-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-16
        • 1970-01-01
        相关资源
        最近更新 更多