【问题标题】:Passing bundles through activities通过活动传递捆绑包
【发布时间】:2014-08-12 06:38:47
【问题描述】:

我有一个捆绑包,我想通过多个活动。

考虑这个例子。我有活动 1、活动 2 和活动 3。 Activity1 转到 Activity2。 Activity2 转到 Activity3。我想从activity1到activity3获取信息

我的代码是

Intent intent = new Intent(v.getContext(), Activity2.class);
intent.putExtra(KEY, "Straight There");
startActivity(intent);

然后我必须在 Activity2 中执行此操作

Bundle extras = getIntent().getExtras();
if (extras != null) 
        text = extras.getString(KEY);
Intent intent = new Intent(v.getContext(), Activity3.class);
intent.putExtra(KEY, text);
startActivity(intent);

无论如何我可以通过 Activity 传递整个捆绑包,而无需解析密钥并重新捆绑?

提前致谢

【问题讨论】:

    标签: android android-intent


    【解决方案1】:

    您可以使用 putExtras(Intent src) 将所有额外内容从一个 Intent 中提取出来,并将它们放入另一个中。

    Intent intent = new Intent(v.getContext(), Activity3.class);
    intent.putExtras(getIntent()); // get all the extras out of the current Activities Intent
    startActivity(intent);
    

    【讨论】:

      【解决方案2】:
      intent.putExtras(getIntent());
      

      【讨论】:

      • 应该是:intent.putExtras(getIntent().getExtras());
      【解决方案3】:

      我认为您可以使用 SharedPreferences 来避免通过活动传递数据活动,如下所示: 在您的第一个活动中,通过 SharedPreferences 保存数据:

      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putString(KEY, "Straight There");
      

      在您的第三个活动中,通过 SharedPreferences 获取数据:

      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      String result = settings.getString(KEY, null);
      

      有关 SharedPreferences 的更多信息,请参阅:Storage Options

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-09
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多