How to pass a value from one Fragment to another in Android?
You can do something like below,
String cid=id.getText().toString();
Fragment fr=new friendfragment();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
Bundle args = new Bundle();
args.putString("CID", cid);
fr.setArguments(args);
ft.replace(R.id.content_frame, fr);
ft.commit();
To receive the data do the following,
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("CID");
return inflater.inflate(R.layout.fragment, container, false);
}
If you want to send data from fragment to activity you may use an interface.
But when you want to send data from fragment to another fragment it get's complicated. You would want to send data to activity and then to the other fragment.
I use EventBus to solve this problem. How it works.
- Create an event-E.
- From Fragment-A register for events.
- From fragment-B publish event-E with data you want to pass.
- You would get the data in onEvent() method you wrote in Fragment-A.
That's it. No need to write your own interfaces.
You may use eventbus for communications from background service or threads to activity also.
Checkout the EventBus HowTo and Repository also.