Android--fragment从activity中获取数据
16lz
2021-01-26
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();
- }
- }
- 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;
- }
- }
更多相关文章
- 一句话锁定MySQL数据占用元凶
- Android(安卓)自动向手机添加联系人(测试数据用)
- Android开发之环形进度条(安卓默认…
- android 原生GET和POST提交数据
- android sensors HAL范例分析
- Android学习笔记(21)————利用JDBC连接服务器数据库
- Mediacodec
- SharedPreferences保存少量的数据
- android项目中单实例数据库类