本文所使用的传值方法时利用接口回调来实现两个Fragment之间的相互传值的.
首先,先创建一个接口:
//这就是接口中的代码,非常简单
public interface SetTextSecond {
public void setText(String s);
}
其次就是在FirstFragment中编写为SecondFragment的信息了
private EditText message;
private Button send;
//设置回调接口
private SetTextSecond setTextSecond;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_frgment,container,false);
//在Fragment里面查找到布局里面的控件,得在findViewByID前边加上前缀变成View.findViewByID,这样就可以进行控件的操作了
message = view.findViewById(R.id.message);
send = view.findViewById(R.id.send_button);
//message控件为EditText,send为Button
//在点击send时,获取message中的信息,然后将信息传入接口中,设置值
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String messageText = message.getText().toString().trim();
if (setTextSecond != null){
setTextSecond.setText(messageText);
}
}
});
return view;
}
//在ONAttach中,Fragment就能获得Activity,在实现SetTextSecond这个回调接口的Activity内,就能实现回调机制
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof SetTextSecond){
setTextSecond = (SetTextSecond) context;
}
}
下面是主函数中的方法
这里的secondFragment只能设置成全局变量,并在onCreate()方法中进行实现.
secondFragment是设置为全局变量的!
@Override
public void setText(String s) {
TextView textView = secondFragment.getView().findViewById(R.id.received);
textView.setText(s);
}
到这里,就可以实现通过Fragment回调方法来进行传值!
下面是没有传值的显示
设置参数:
点击发送之后,的成功页面!
到此结束Fragment之间的参数传递!
布局参照上一个博客!