github地址
一、使用接口,通过Activity宿主作为中间桥梁,进行数据交互
1)定义数据接口
2)在Activity中实现该接口,并实现接口中定义的方法
3)在Fragment A中声明接口对象,并调用接口中的方法
4)Activity中的接口回调中,向Fragment B传递数据
关键代码
接口:
public interface IAddListener {
void update(int count); //更新数据
}
AFragment:
public class AFragment extends Fragment {
private int count; //计数器,表示向Fragment B传递的数据
private IAddListener listener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
initView(view);
return view;
}
//初始化View
private void initView(View view) {
view.findViewById(R.id.btn_add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//数字加1,向Fragment B传递数据
count++;
listener.update(count); //传递数据
this.listener = listener;
}
}
Activity:
public class MainActivity extends AppCompatActivity implements IAddListener{
private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFragment();
}
//初始化Fragment
private void initFragment() {
fragmentManager = getSupportFragmentManager();
AFragment aFragment = new AFragment();
FragmentTransaction transaction =
fragmentManager.beginTransaction();
transaction.add(R.id.fragment_a,aFragment,"AFragment");
transaction.add(R.id.fragment_b,new BFragment(),"BFragment");
transaction.commit();
aFragment.setIAddListener(this); //传递接口对象
}
//回调的接口
@Override
public void update(int count) {
BFragment bFragment = (BFragment) fragmentManager.findFragmentByTag("BFragment");
bFragment.update(count);
}
}
BFragment:
public class BFragment extends Fragment {
private TextView resultTv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
initView(view);
return view;
}
//初始化View
private void initView(View view) {
resultTv = (TextView) view.findViewById(R.id.result_tv);
}
//供Activity调用的方法
public void update(int count) {
resultTv.setText(String.valueOf(count));
}
}
二、EventBus传值
关键代码
AFragment:
EventBus.getDefault().post(Integer.valueOf(count));
BFragment:
@Overridepublic void onAttach(Context context) {
super.onAttach(context);
//注册
EventBus.getDefault().register(this);}
@Overridepublic void onDestroyView() {
super.onDestroyView(); //解绑
EventBus.getDefault().unregister(this);
}
//事件接收
@Subscribe
public void onEvent(Integer count){
resultTv.setText(String.valueOf(count));
Toast.makeText(getContext(), "传递数据成功", Toast.LENGTH_SHORT).show();
}