【问题标题】:Get Activity's 1 Intent extras from Activity's 2 static fragment从 Activity 的 2 静态片段中获取 Activity 的 1 Intent extras
【发布时间】:2019-02-16 15:10:07
【问题描述】:

我有以下情况。我使用 Intent 从SelectRecipeActivity 转到RecipeStepsActivity。我使用捆绑包来传递配方成分和步骤。 RecipeStepsActivity 托管一个静态片段 (RecipeStepsFragment),其中显示了配方的成分和步骤。我的问题是将意图包传递给RecipeStepsFragment 的最佳实践是什么?

现在我在RecipeStepsFragmentonCreateView() 中使用getActivity().getIntent().getExtras()SelectRecipeActivity 获取intent 的额外内容,它可以正常工作。

由于它不是动态片段(我不使用片段构造函数或 newInstance 方法,它是使用<fragment> 标签在 xml 中声明的)并且没有发生片段事务,我无法使用片段参数,我知道这是推荐的方式。或者我可以吗?我错过了什么吗?谢谢!!

【问题讨论】:

    标签: android android-intent fragment android-bundle


    【解决方案1】:

    好的,我假设您只是指由“静态”在 xml 中定义的片段,而不是静态变量(这对于片段来说是一件非常糟糕的事情)。在这种情况下 - 给片段一个 id,在 Activity 的 onCreate 中使用 findFragmentById,将其转换为正确的片段类型,然后在片段上调用一个函数来传递适当的数据。

    【讨论】:

      【解决方案2】:

      按照@Gabe Sechan 的建议,我使用以下方式将捆绑包从RecipeStepsActivity 传递给RecipeStepsFragment

      1) 我收到了从SelectRecipeActivityRecipeStepsActivityonCreate 方法的intent extra。

      2) 在RecipeStepsActivityonCreate 方法中,我通过像这样调用findFragmentById 来获得对RecipeStepsFragment 的引用:

      RecipeStepsFragment stepsFragment = (RecipeStepsFragment)getSupportFragmentManager()
      .findFragmentById(R.id.master_steps_fragment);
      

      3) 然后我获得了创建 Bundle 的意图附加信息,然后我将其作为 RecipeStepsFragment 的参数传递,如下所示:

      Bundle args = getIntent().getExtras();
      //Pass the intent extras to the fragment using a bundle
      if (args != null) {
         //show Dessert Name in Toolbar
         mRecipe = args.getParcelable(EXTRAS_RECIPE_ITEM);
         assert mRecipe != null;
         setTitle(mRecipe.getName());
      
         assert stepsFragment != null;
         stepsFragment.setArguments(args);
      }
      

      4) 现在在RecipeStepsFragment's ->onActivityCreated

      Bundle fragmentArgs = getArguments();
      

      其中包含与传递给RecipeStepsActivity 相同的额外SelectRecipeActivity

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多