Android--fragment从activity中获取数据

MainActivity:

  1. public class MainActivity extends Activity {  
  2.     private FragmentManager manager;  
  3.     private FragmentTransaction transaction;  
  4.   
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_main);  
  9.   
  10.         manager = getFragmentManager();  
  11.         transaction = manager.beginTransaction();  
  12.   
  13.         MyFragment1 fragment1 = new MyFragment1();  
  14.         Bundle bundle1 = new Bundle();  
  15.         bundle1.putString("id""Activity发送给MyFragment1的数据");  
  16.         fragment1.setArguments(bundle1);  
  17.         transaction.replace(R.id.left, fragment1, "left");  
  18.   
  19.         MyFragment2 fragment2 = new MyFragment2();  
  20.         Bundle bundle2 = new Bundle();  
  21.         bundle2.putString("id""Activity发送给MyFragment2的数据");  
  22.         fragment2.setArguments(bundle2);  
  23.         transaction.replace(R.id.right, fragment2, "right");  
  24.   
  25.         transaction.commit();  
  26.     }  
  27.   

MyFragment1:

  1. public class MyFragment1 extends Fragment {  
  2.     @Override  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.     }  
  6.   
  7.     @Override  
  8.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  9.             Bundle savedInstanceState) {  
  10.         View view = inflater.inflate(R.layout.f1, null);  
  11.           
  12.         TextView textView = (TextView) view.findViewById(R.id.textView);  
  13.         Bundle bundle1 = getArguments();  
  14.         textView.setText(bundle1.getString("id"));  
  15.         return view;  
  16.     }  
  17.   
  18. }  

MyFragment2

  1. public class MyFragment2 extends Fragment {  
  2.     @Override  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.     }  
  6.   
  7.     @Override  
  8.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  9.             Bundle savedInstanceState) {  
  10.         View view = inflater.inflate(R.layout.f2, null);  
  11.           
  12.         TextView textView = (TextView) view.findViewById(R.id.textView);  
  13.         Bundle bundle2 = getArguments();  
  14.         textView.setText(bundle2.getString("id"));  
  15.         return view;  
  16.     }  
  17.   
  18. }  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值