public interface IFragmentDataListener {
public void transferMessage();
}
2.然后Fragment和FragmentActivity分别取实现IFragmentDataListener接口:public class CompanyContactsFragment extends BaseFragment<CompanyContactsFragment> implements IFragmentDataListener
public class CompanyActivity extends BaseFragmentActivity<CompanyActivity> implements IFragmentDataListener
3.如果FragmentActivity中调用Fragment的方法:
在FragmentActivity中:
- private IFragmentDataListener mFragmentDataListener;
- @Override
- public void onAttachFragment(Fragment fragment) {
- // TODO Auto-generated method stub
- try {
- mFragmentDataListener = (IFragmentDataListener) fragment;
- } catch (Exception e) {
- // TODO: handle exception
- }
- super.onAttachFragment(fragment);
- }
- @Override
- public void transferMessage() {//在这里这个不用管
- // TODO Auto-generated method stub
- System.out.println("由Fragment传输过来的信息");
- }
- mFragmentDataListener.transferMessage();//在需要调用的地方,调用这个方法
在Fragment中:
- @Override
- public void transferMessage() {
- // TODO Auto-generated method stub
- System.out.println("由Activity传输过来的信息");
- loadData(2);
- }
4.在Fragment中调用FragmentActivity中的方法:
在FragmentActivity中:
- @Override
- public void transferMessage() {
- // TODO Auto-generated method stub
- System.out.println("由Fragment传输过来的信息");
- setTitleButtonSelect(1);
在Fragment中:
- private IFragmentDataListener mFragmentDataListener;
- @Override
- public void onAttach(Activity activity) {
- // TODO Auto-generated method stub
- try {
- mFragmentDataListener = (IFragmentDataListener) activity;
- } catch (Exception e) {
- // TODO: handle exception
- throw new ClassCastException(activity.toString()+ "must implement mbtnListener");
- }
- super.onAttach(activity);
- }
- @Override
- public void transferMessage() {//在这里这个不用管
- // TODO Auto-generated method stub
- System.out.println("由Activity传输过来的信息");
- }
- mFragmentDataListener.transferMessage();//在需要调用的地方,调用这个方法
秋#@ 于 2016/09/06 13:09 评论
在安卓开发上fragment通信最好的办法,学习了。。。