从Activity的2个静态片段中获取Activity的1个Intent附加内容

时间:2019-02-16 15:10:07

标签: android android-intent fragment android-bundle

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

现在,我在getActivity().getIntent().getExtras()的{​​{1}}中使用RecipeStepsFragment来从onCreateView()获取意图的附加内容,并且没有问题。

由于它不是动态片段(我不使用Fragment构造函数或newInstance方法,而是使用SelectRecipeActivity标签在xml中声明),并且没有发生片段事务,因此我无法通过使用片段参数的其他功能,我知道这是推荐的方式。可以吗我想念什么吗?谢谢!!

2 个答案:

答案 0 :(得分:1)

好吧,我假设您的意思是在xml中通过“静态”定义的片段,而不是静态变量(对于片段而言,这确实是一件坏事)。在这种情况下,给该片段一个ID,在Activity的onCreate中使用findFragmentById,将其转换为正确的Fragment类型,然后在Fragment上调用一个函数以将适当的数据传递给它。

答案 1 :(得分:0)

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

1)我收到了从SelectRecipeActivityRecipeStepsActivity的{​​{1}}方法的意图额外内容。

2)在onCreate的{​​{1}}方法中,我通过调用RecipeStepsActivity来获得对onCreate的引用,如下所示:

RecipeStepsFragment

3)然后,我获得了意图创建findFragmentById的附加功能,然后将其作为RecipeStepsFragment stepsFragment = (RecipeStepsFragment)getSupportFragmentManager() .findFragmentById(R.id.master_steps_fragment); 的参数传递,如下所示:

Bundle

4)现在,在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); } <-方法中(确保已创建了托管活动,因此我们从先前的活动中获得了额外的意图),只需获得该步骤的3个参数即可:

RecipeStepsFragment

其中包含传递给onActivityCreated的相同附加内容Bundle fragmentArgs = getArguments();

相关问题