Data exchange between Fragment and Activity generally includes three types:
1. Fragment obtains data from the Activity (this article only introduces the first type );
2. Activity obtains data from Fragment;
3. Get data between Fragment.
Implementation:
Data is transmitted from the Activity to two Fragment. After the Fragment obtains the data, it is displayed.
Source code:
Layout file:
Activity_main:
Layout file f1 of MyFragment1:
Layout file f2 of MyFragment2:
Code file:
MainActivity:
Package com. fragmentdemo5_commute; import android. app. activity; import android. app. fragmentManager; import android. app. fragmentTransaction; import android. OS. bundle;/*** 1. Fragment obtains data from the Activity. */Public class MainActivity extends Activity {private FragmentManager manager; private FragmentTransaction transaction; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); manager = getFragmentManager (); transaction = manager. beginTransaction (); MyFragment1 fragment1 = new MyFragment1 (); Bundle bundle1 = new Bundle (); bundle1.putString ("id", "data sent by Activity to MyFragment1 "); fragment1.setArguments (bundle1); transaction. replace (R. id. left, fragment1, "left"); MyFragment2 fragment2 = new MyFragment2 (); Bundle bundle2 = new Bundle (); bundle2.putString ("id ", "Activity sends data to MyFragment2"); fragment2.setArguments (bundle2); transaction. replace (R. id. right, fragment2, "right"); transaction. commit ();}}
MyFragment1:
package com.fragmentdemo5_commute;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;public class MyFragment1 extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.f1, null);TextView textView = (TextView) view.findViewById(R.id.textView);Bundle bundle1 = getArguments();textView.setText(bundle1.getString("id"));return view;}}
MyFragment2:
package com.fragmentdemo5_commute;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;public class MyFragment2 extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.f2, null);TextView textView = (TextView) view.findViewById(R.id.textView);Bundle bundle2 = getArguments();textView.setText(bundle2.getString("id"));return view;}}
Source code download:
Click to download source code