25. Activity与Fragment通信
25.1 Activity与Fragment通信
原生方案: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);
运行
25.2 动态添加Fragment的过程总结
创建一个待处理的fragment
获取fragmentManager,一般通过getSupportFragmentManager()
开启一个事务transaction,一般调用fragmentManager的beginTransation()
使用transaction进行fragment切换
提交事务
25.3 Activity与Fragment通信方案:Java接口
Java中类与类自己通信的常用方案:接口
定义接口
package com.dingjiaxiong.myfragmentmanagers;
public interface IFragmentCallBack {
void sendMsgToActivity(String string);
String getMsgFromActivity(String msg);
}
1
2
3
4
5
6
7
8
9
修改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";
}
});
运行
成功
25.4 其他方案
eventBus、LiveData
【观察者设计模式】
【发布订阅】
标签:25,layout,String,Fragment,fragment,Activity,public From: https://www.cnblogs.com/55zjc/p/16706488.html