Activity之间通信
- Intent / Bundle
- 类静态变量
- 全局变量
Activity与Fragment通信
-
Activity将数据传递给Fragment
- 通过Bundle
public class FragmentActivity1 extends Activity { public String productId; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = new Bundle(); bundle.putString(Constant.INTENT_ID, productId); Fragment fragment = new Fragment1(); fragment.setArguments(bundle); } }
public class Fragment1 extends Fragment { public String productId; @Override public void onStart() { super.onStart(); if (isAdded()) {//判断Fragment已经依附Activity productId = getArguments().getString(Constant.INTENT_ID); } } }
- 在Activity中定义方法
public class FragmentActivity2 extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public String getTitles(){ return "getTitle"; } }
public class Fragment2 extends Fragment { public String titles; @Override public void onAttach(Context context) { super.onAttach(context); titles = ((FragmentActivity2) context).getTitles();//通过强转成宿主activity,就可以获取到传递过来的数据 } }
-
Fragment将数据传递给Activity
1.在Fragment中定义一个内部接口回调
2.Activity实现该接口回调
3.在Fragment的OnAttach()
中获得实现了该接口的Activity
4.在Fragment的OnDetach()
中把传递进来的Activity对象释放掉public class Fragment3 extends Fragment implements View.OnClickListener { // 2.1 定义用来与外部activity交互,获取到宿主activity private FragmentListener listener; // 1 定义了所有activity必须实现的接口方法 public interface FragmentListener { void process(String str); } // 当Fragment被加载到activity的时候会被回调 @Override public void onAttach(Activity activity) { super.onAttach(activity); if(activity instanceof FragmentListener) { listener = (FragmentListener)activity; // 2.2 获取到宿主activity并赋值 } else{ throw new IllegalArgumentException("activity must implements FragmentListener"); } } @Override public void onClick(View v) { listener.process("我是接口"); //3.1 执行回调 } //把传递进来的activity对象释放掉 @Override public void onDetach() { super.onDetach(); listener = null; } }
public class FragmentActivity3 extends Activity implements Fragment3.FragmentListener { @Override public void process(String str) { //todo } }