两个单独的Fragment是 不应该进行通信的,应该用他们所在的activity作为 通信的纽带。
为了实现 两个Fragment的交互,我们在Fragment中定义一个接口,然后在中定义 一个方法,在
Fragment的onAttach()方法中调用这个接口中的方法,然后让Activity实现这个方法,来完成
Activity和Fragment之间的通信 。
public class HttpFragment extends Fragment { public static HttpFragment newInstance(){ HttpFragment httpFragment= new HttpFragment(); Log.e("HttpFragment", "newInstance"); return httpFragment; } private ChangeTitleCallbacks changeTitleCallbacks; /** * this is for change the title * @author lsj * 2014.8.7 */ public static interface ChangeTitleCallbacks{ public void onSectionAttached(int number); } @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); try { changeTitleCallbacks=(ChangeTitleCallbacks)activity; changeTitleCallbacks.onSectionAttached(SectionConstant.HTTP_SECTION); } catch (ClassCastException e) { throw new ClassCastException("Activity must implement ChangTitleCallbacks."); } }
在MainActivity 中实现 了onSectionAttached();
Fragment间的交互
时间: 2024-10-10 04:59:34