Fragment与Activity之间的相互通信

时间:2021-06-21 01:48:00

https://blog.csdn.net/u012702547/article/details/49786417

https://blog.csdn.net/carson_ho/article/details/75453770

一、接口方式
在fragment类中定义一个接口并在Activity中实现它。Fragment在onAttach()回调函数中获取接口的具体实现的对象。后面,fragment就可以调用接口中的方法实现与Activity的通信。

在Android5.0之后废除了onAttach(Activity activity)的方法,转而使用onAttach(Context context),也就是传递的参数发生变化

public interface showMsgListener{
void showMsg(String str);
} private showMsgListener msgListener; @Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
if(activity!=null){
msgListener=(MainActivity)activity;
}
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement showMsgListener");
}
} mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
msgListener.showMsg("Hello Android!(接口)");
}
});

在Activity中需要实现该接口

 @Override
public void showMsg(String str) {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}

二、广播

在Activity中注册广播接收器,在Fragment中发送广播

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ACTION_NAME)) {
String msg = intent.getStringExtra("msg");
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
} }
}; public void registerBoradcastReceiver() {
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction(ACTION_NAME);
registerReceiver(mBroadcastReceiver, myIntentFilter);
} @Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBroadcastReceiver);
}

三、Fragment 从Activity获取数据

在Fragment 的getInstance()方法中setArguments()设置参数

public static Fragment getInstance(String msg){
Bundle bundle = new Bundle();
bundle.putString("msg",msg);
MainFragment fragment=new MainFragment();
fragment.setArguments(bundle);
return fragment;
}

再通过getArguments()方法获取

 public void initDatas() {
Bundle bundle=getArguments();
if(bundle!=null){
String msg=bundle.getString("msg");
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
}