如何在Android中的活动之间传递变量?

时间:2018-09-21 13:20:52

标签: android

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

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

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

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

3 个答案:

答案 0 :(得分:0)

onActivityResult()startActivityForResult()一起使用。

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

答案 1 :(得分:0)

您可能正在寻找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.
    }

答案 2 :(得分:0)

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

然后,您可以在locationSelectionFragment.setTargetFragment(this);中使用MainPostFragment,然后再将其添加到Activity的片段事务中,这使您可以使用getTargetFragment()来传回值:

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

但是还有其他多种选择,每种选择各有优缺点as described in this article

相关问题