Fragment与Activity的通信(回调),Fragment间的通信

一、消息Fragment-->Activity

1、Fragment启动Activity时通过Intent将数据传递过去,这种方法每次都要重启Activity。

2、通过回调方法:

  2.1 普通的回调方法。


Fragment类中定义方法switch
private void switch(Fragment f) {
	if(f != null){
		if(getActivity() instanceof MainActivity){
			((MainActivity)getActivity()).switchFragment(f);
		}
	}
}
        该方法MainActivity 的实例,实现调用MainActivity 中的方法实现通信。
       MainActivity类中对应的回调方法switchFragment(Fragment f)完成响应。

  2.2 通过接口实现回调:


    2.2.1 在Fragment类中定义接口及抽象方法,并在onAttach方法中添加如下代码:
private OnFragmentChangeListener mCallBack;

public interface OnFragmentChangeListener {
	public void onTabSwitch(int position);
}

@Override
public void onAttach(Activity activity) {
	super.onAttach(activity);
	//确保包含Fragment的Activity已经实现了回调接口,否则抛出异常
	try {
		mCallBack = (OnFragmentChangeListener) activity;
	} catch (Exception e) {
		throw new ClassCastException(activity.toString()
					+ " must implement OnFragmentChangeListener");
	}
}
    2.2.2 在Activity中实现上面的接口:
public class TestActivity extends Activity implements
		MyFragment.OnFragmentChangeListener {
	@Override
	public void onTabSwitch(int position) {
		//此处接收事件的回调
	}
}
    2.2.3 在Fragment将信息发送给父Activity:
mCallBack.onTabSwitch(pos);

      两种回调方法都很适用于通过Fragment切换Activity的页面。

二、消息从Activity-->Fragment

1、通过实例化一个Fragment

    在Activity中设置如下代码携带参数传递给Fragment:
Fragment2 newFragment = new Fragment2();
Bundle args = new Bundle();
args.putInt(Fragment2.ARG_KEY, position);
newFragment.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.frame, newFragment).commit();

   或者通过构造方法将数据传递给Fragment(官方不推荐):
Fragment2 newFragment = new Fragment2(arg1,arg2);


推荐做法:

1.1在Fragment中

public static MyFragment newInstance(String userName, String password) {
		MyFragment frgmt = new MyFragment();
		Bundle args = new Bundle();
		args.putString("userName", userName);
		args.putString("password", password);
		frgmt.setArguments(args);
		return frgmt;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (null != getArguments()) {
			String userName = getArguments().getString("userName");
			String password = getArguments().getString("password");
		}
	}


1.2Activity中调用:

MyFragment myFragment = MyFragment.newInstance("myName", "myPsw");


2、通过findFragmentById()或者findFragmentByTag()方法找到Fragment的实例:


MyFragment fragment = (MyFragment) getFragmentManager().findFragmentById(R.id.frame);
if(fragment!=null){
	fragment.frgmtFunc();
}

参考自: http://blog.csdn.net/xyz_lmn/article/details/8631195#t1













    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值