MainActivity:
- public class MainActivity extends Activity {
- private FragmentManager manager;
- private FragmentTransaction transaction;
- @Override
- protected 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", "Activity发送给MyFragment1的数据");
- fragment1.setArguments(bundle1);
- transaction.replace(R.id.left, fragment1, "left");
- MyFragment2 fragment2 = new MyFragment2();
- Bundle bundle2 = new Bundle();
- bundle2.putString("id", "Activity发送给MyFragment2的数据");
- fragment2.setArguments(bundle2);
- transaction.replace(R.id.right, fragment2, "right");
- transaction.commit();
- }
- }
MyFragment1:
- public class MyFragment1 extends Fragment {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- }
- @Override
- public 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
- public class MyFragment2 extends Fragment {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- }
- @Override
- public 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;
- }
- }