学会了在Activity中加载Fragment的方法之后,接下来便需要学习Activity和Fragment之间的通信。这一节先学习如何把Activity中的信息传递给Fragment。
基本过程
在Activity中创建Bundle数据包来存储需要传输的数据,然后调用Fragmen类的setArugments方法来把Bundle数据包传输给Fragment。在Fragment中利用getArugments的方法,便可以根据相应的Key值来获取到传输的数据。
代码实现
一、在Activity中创建Bundle数据包
public void onClick(View v) {
String text = editText.getText()+""; //小技巧:可以强制转换成String类型
Fragment3 fragment3 =new Fragment3();
Bundle bundle=new Bundle();
bundle.putString("text",text); //设置Key值,用于Fragment获取数值
fragment3.setArguments(bundle);
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.layout,fragment3); //注意,此处要用replace,否则只会显示第一次输入的数据
fragmentTransaction.commit(); //commit必不可少 }
二、在Fragment中用getArguments方法来获取数据
View view=inflater.inflate(R.layout.fragment_1,container,false);
String text = getArguments().get("text").toString();
tv= (TextView) view.findViewById(R.id.textview);
tv.setText(text);
return view;