1// In Fragment_1.java
2
3Bundle bundle = new Bundle();
4bundle.putString("key","abc"); // Put anything what you want
5
6Fragment_2 fragment2 = new Fragment_2();
7fragment2.setArguments(bundle);
8
9getFragmentManager()
10 .beginTransaction()
11 .replace(R.id.content, fragment2)
12 .commit();
13
14
15// In Fragment_2.java
16
17Bundle bundle = this.getArguments();
18
19if(bundle != null){
20 // handle your code here.
21}
1public class FragmentB extends Fragment{
2 final static String DATA_RECEIVE = "data_receive";
3 TextView showReceivedData;
4
5 @Override
6 public View onCreateView(LayoutInflater inflater, ViewGroup container,
7 Bundle savedInstanceState) {
8 View view = inflater.inflate(R.layout.fragment_B, container, false);
9 showReceivedData = (TextView) view.findViewById(R.id.showReceivedData);
10 }
11
12 @Override
13 public void onStart() {
14 super.onStart();
15 Bundle args = getArguments();
16 if (args != null) {
17 showReceivedData.setText(args.getString(DATA_RECEIVE));
18 }
19 }
20}
21
1public class FragmentA extends Fragment
2{
3 DataPassListener mCallback;
4
5 public interface DataPassListener{
6 public void passData(String data);
7 }
8
9 @Override
10 public void onAttach(Context context)
11 {
12 super.onAttach(context);
13 // This makes sure that the host activity has implemented the callback interface
14 // If not, it throws an exception
15 try
16 {
17 mCallback = (OnImageClickListener) context;
18 }
19 catch (ClassCastException e)
20 {
21 throw new ClassCastException(context.toString()+ " must implement OnImageClickListener");
22 }
23 }
24
25 public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
26 {
27 // Suppose that when a button clicked second FragmentB will be inflated
28 // some data on FragmentA will pass FragmentB
29 // Button passDataButton = (Button).........
30
31 passDataButton.setOnClickListener(new OnClickListener() {
32 @Override
33 public void onClick(View v) {
34 if (view.getId() == R.id.passDataButton) {
35 mCallback.passData("Text to pass FragmentB");
36 }
37 }
38 });
39 }
40}
41
1public class MainActivity extends ActionBarActivity implements DataPassListener{
2
3 @Override
4 protected void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.activity_main);
7
8 if (findViewById(R.id.container) != null) {
9 if (savedInstanceState != null) {
10 return;
11 }
12 getFragmentManager().beginTransaction()
13 .add(R.id.container, new FragmentA()).commit();
14 }
15 }
16
17 @Override
18 public void passData(String data) {
19 FragmentB fragmentB = new FragmentB ();
20 Bundle args = new Bundle();
21 args.putString(FragmentB.DATA_RECEIVE, data);
22 fragmentB .setArguments(args);
23 getFragmentManager().beginTransaction()
24 .replace(R.id.container, fragmentB )
25 .commit();
26 }
27}
28