I have a navigation drawer which contains different fragments (each item display a fragment) and i\'d like to pass data from a fragment to another.(I have just one activity
When you click inside your NavigationDrawer
, you can use setArguments()
method to declare your datas via a Bundle
as follows:
// int id = 1;
MyFragment newFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("ARG_DATA_ID", id);
newFragment.setArguments(args);
// replace and commit with fragmenttransaction
Then, inside your Fragment, use getArgument()
method like the following:
Bundle arg = getArguments();
int id_pass = arg.getInt("ARG_DATA_ID");
// id_pass = 1;
However, maybe you can find some useful tips into this topic: Communicating with Other Fragments.
UPDATE:
Well, I tried to make an example from your code but, it's hum.. hard ;).
You don't receive an argument because in SelectItem
method, you don't send any argument with Menu
fragment (but your switch is how to do, you're on the right way). You try separatly to send an argument but in other Bundle
when you click on buttonValidatePrices
in setting
which it is not send or anything. Just created, a value stored into it, and nothing.. it's not related to the FragmentTransaction
.
Inside Menu
, you try to receive with this:
Log.i("bundlebundlebundle", getArguments().getString("price_"+"pizza",Default));
But I think it will be better with:
Log.i("bundlebundlebundle", getArguments().getString("price_pizza"));
You should:
First (in MainActivity) = get the value of the clicked spinner from MainActivity
to your setting
Fragment, create a Bundle and set this value to the fragment inside SelectItem
method as follows:
switch(...) {
case 2:
frag = new Menu();
// get the value of the spinner selected from here! Something like this:
String text = ((Spinner) findViewById(R.id.spinnerSetting)). getSelectedItem().toString();
// String named "spinner_position", this is how you can get it after
args.putString("spinner_position", text);
break;
...
}
frag.setArguments(args);
// replace the fragment
Second (in Menu) = receive this argument as follows:
// receive using the name "spinner_position", that's it. Nothing else.
String text_spinner = getArguments().getString("spinner_position");
You could use a http://developer.android.com/reference/android/content/BroadcastReceiver.html
Or you could set the listener of each fragment as your activity, and send data from a fragment to an activity and call methods directly on the other fragment from the activity.