How to communicate data between two fragments in a navigation drawer

不打扰是莪最后的温柔 提交于 2019-12-01 21:12:13

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 ;).

  1. 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.

  2. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!