I have the following scenario. I use an Intent to go from SelectRecipeActivity
to RecipeStepsActivity
. I use a bundle to pass the recipe ingredients and steps with this intent. RecipeStepsActivity
hosts a static fragment (RecipeStepsFragment
) where the recipe's ingredients and steps are being shown. My question is what is the best practice to pass the intent bundle to the RecipeStepsFragment
?
Right now I use getActivity().getIntent().getExtras()
in RecipeStepsFragment
's onCreateView()
to get the intent's extras from SelectRecipeActivity
and it works with no problems.
As it is not a dynamic fragment (I don't use a Fragment constructor or newInstance method, it is declared in xml using the <fragment>
tag) and a fragment transaction is not taking place, I cannot pass the extras using fragment arguments, which I know is the recommended way. Or can I? Am I missing something? Thank you!!
Following @Gabe Sechan's proposal, I used the following way to pass the bundle to RecipeStepsFragment
from RecipeStepsActivity
.
1) I receive the intent extras from SelectRecipeActivity
to RecipeStepsActivity
's onCreate
method.
2) In RecipeStepsActivity
's onCreate
method I get a reference to RecipeStepsFragment
by calling findFragmentById
like this:
RecipeStepsFragment stepsFragment = (RecipeStepsFragment)getSupportFragmentManager()
.findFragmentById(R.id.master_steps_fragment);
3) Then I get the intent extras creating a Bundle
, which I then pass as RecipeStepsFragment
's arguments, like this:
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) Now in RecipeStepsFragment
's ->onActivityCreated
<- method (to be sure that the hosting activity has been created and so we have got the intent extras from the previous activity), I simply get the step's 3 arguments like this:
Bundle fragmentArgs = getArguments();
which contains the same extras SelectRecipeActivity
passed to the RecipeStepsActivity
.