Fragment与Activity通信
- Fragment可调用getActivity()方法获取它所在的Activity
- Activity可调用FragmentManager的findFragmentById()或findFragmentByTag()方法获取Fragment
- Activity ——> Fragment: 在Activity中创建Bundle数据包,并调用Fragment的setArguments(Bundle bundle)方法
- Fragment ——> Activity: 在Fragment中定义一个内部回调接口,再让含该Fragment的Activity实现该回调接口。这样Fragment可调用该回调方法将数据传递给Activity
Activity向Fragment传递数据
1.动态加载Fragment时
Activity中代码:
MoveFragment moveFragment = new MoveFragment();
Bundle bundle = new Bundle();
bundle.putString("name","Activity向Fragment传递数据");
moveFragment.setArguments(bundle);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.frame,moveFragment,"fragment_move");
transaction.addToBackStack(null);
transaction.commit();
Fragment中代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//layout布局文件转换成View对象
/*
Inflate the layout for this fragment
resource: Fragment需要加载的布局文件
root: 加载layout的父ViewGroup
attachToRoot: false, 不返回父ViewGroup
*/
View view = inflater.inflate(R.layout.fragment_blank, container, false);
TextView textView = view.findViewById(R.id.textView);
String text = getArguments() != null ? getArguments().getString("name") : null;
textView.setText(text);
return view;
}
2.静态加载Fragment时
调用FragmentManager的findFragmentById()或findFragmentByTag()方法获取Fragment
Activity中代码
FragmentManager fm = getSupportFragmentManager();
Fragment fragmentById = fm.findFragmentById(R.id.ft_load_static);
BlankFragment fragment = (BlankFragment) fragmentById;
fragment.setTransfer("Activity向静态加载的Fragment发送消息");
Fragment中代码
private String transfer;
public String getTransfer() {
return transfer;
}
public void setTransfer(String transfer) {
this.transfer = transfer;
}
view.findViewById(R.id.receive).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "Fragment接收消息:" + getTransfer(), Toast.LENGTH_SHORT).show();
}
});
Fragment向Activity传递数据
1.Fragment中定义接口
public interface MyListener{
void send(String text);
}
2.onAttach中
@Override
public void onAttach(@NonNull Context context) {
listener = (MyListener) context;
super.onAttach(context);
}
3.onCreateView中调用接口发送消息
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
listener.send("Fragment向Activity传递数据");
return view;
}
Activity实现Fragment中定义的接口来接收数据
@Override
public void send(String text) {
Toast.makeText(this,"来自Fragment:"+ text,Toast.LENGTH_SHORT).show();
}