原生方案:Bundle
如何让Activity和BlankFragment1完成通信
Activity中:
//定义一个bundle
Bundle bundle = new Bundle();
//放入数据,构建bundle
bundle.putString("message","dingjiaxiong");
//构建一个blankfragment
BlankFragment1 bf = new BlankFragment1();
//放入bundle
bf.setArguments(bundle);
//进行切换
replaceFragment(bf);
在fragment中
//获取bundle
Bundle bundle = this.getArguments();
//获取数据
String s = bundle.getString("message");
Log.e("dingjiaxiong", "onCreate: " + s);
运行
Java中类与类自己通信的常用方案:接口
定义接口
package com.dingjiaxiong.myfragmentmanagers;
public interface IFragmentCallBack {
void sendMsgToActivity(String string);
String getMsgFromActivity(String msg);
}
修改fragment布局
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn3"
android:layout_gravity="center"
android:text="数据传递"
/>
在Fragment中定义对象并在Oncreate生命周期中实现发送消息
private IFragmentCallBack fragmentCallBack;
public void setFragmentCallBack(IFragmentCallBack callBack){
fragmentCallBack = callBack;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(rootView == null){
rootView = inflater.inflate(R.layout.fragment_blank1, container, false);
}
Button button = rootView.findViewById(R.id.btn3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fragmentCallBack.sendMsgToActivity("Hello,我来自fragment");
}
});
return rootView;
}
在Activity中调用实现接口
bf.setFragmentCallBack(new IFragmentCallBack() {
@Override
public void sendMsgToActivity(String string) {
Toast.makeText(MainActivity.this,string , Toast.LENGTH_SHORT).show();
}
@Override
public String getMsgFromActivity(String msg) {
return null;
}
});
运行
同理,fragment从activity中获取消息
bf.setFragmentCallBack(new IFragmentCallBack() {
@Override
public void sendMsgToActivity(String string) {
Toast.makeText(MainActivity.this,string , Toast.LENGTH_SHORT).show();
}
@Override
public String getMsgFromActivity(String msg) {
return "hello ,我来自activity";
}
});
运行
成功
eventBus、LiveData
【观察者设计模式】
【发布订阅】