Fragment与Activity通信详解
扫描二维码
随时随地手机看文章
动态加载的Fragment
Activity => Fragment
实例化 bundle类 传递给 Fragment
//动态加载 fragment Fragment fragment = new Fragment(); //这个是我们自己定义的 Fragment FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //实例化bundle类 Bundle bundle = new Bundle(); bundle.putString("title","学习雷锋好榜样"); //传递数据 fragment.setArguments(bundle); fragmentTransaction.addToBackStack(null); //后退按键 允许 fragmentTransaction.add(R.id.linear,fragment); fragmentTransaction.commit();
Fragment =>Activity
实质就是调用Activity中的方法
Fragment.java
public interface MyListener{ public void sayHello(String str); } @Override public void onAttach(Activity activity) { MyListener listener = (MyListener)getActivity(); listener.sayHello("Fragment 传递给 Activity 的数据!"); super.onAttach(activity); }
MainActivity.java
public class MainActivity extends ActionBarActivity implements Fragment.MyListener ... ... @Override public void sayHello(String str) { Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show(); }
静态加载的Fragment
Activity => Fragment
实质就是调用Fragment类中的方法
public class Fragment extends android.app.Fragment { private String str; public void setStr(String str) { this.str = str; } public String getStr() { return str; }
MainActivity.java
FragmentManager fragmentManager = getFragmentManager(); android.app.Fragment fragmentById = fragmentManager.findFragmentById(R.id.fragment); Fragment fragment = (Fragment)fragmentById; fragment.setStr("123");
注意:Fragment 的 onCreateView的时候,Activity中的 setStr没有执行
所以是无法在接收到的
“
Fragment =>Activity (和动态加载一致)