Getting Arguments From A Bundle
I'm trying to pass arguments from my Activity to a Fragment and I'm using this code: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(sav
Solution 1:
The best way to use arguments with your fragment is to use the newInstance function of the fragment.Create a static method that gets your params and pass them in the fragment through the new instance function as below:
publicstatic myFragment newInstance(String param1, String param2) {
myFragment fragment = new myFragment ();
Bundle args = newBundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
And then on create set your global arguments:
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
on your main activity you will create the fragment like
myFragment__myFragment= myFragment.newInstance("test","test");
That should work
Solution 2:
This is a correct approach
Send (in the Activity):
finalFragmentTransactionft= getSupportFragmentManager().beginTransaction();
finalDetailActivityFragmentfrg=newDetailActivityFragment ();
ft.replace(R.id.container, frg);
finalBundlebdl=newBundle();
bdl.putString("yourKey", "Some Value");
frg.setArguments(bdl);
ft.commit();
Receive (in the Fragment):
finalBundlebdl= getArguments();
Stringstr="";
try
{
str = bdl.getString("yourKey");
}
catch(final Exception e)
{
// Do nothing
}
Post a Comment for "Getting Arguments From A Bundle"