[英]How to get value from one fragment and pass to another fragment
我有两个片段,一个是片段X和片段y。片段X用于使用Web服务的注册过程。 我想将相同的值从Fragment X传递给FragmentY。
这是我的代码:
片段x:
Signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String sName = Name.getText().toString(); String sPhoneNo = Phone.getText().toString(); String sEmailId = EmailId.getText().toString(); // Instantiate Http Request Param Object RequestParams params = new RequestParams(); if (Utility.isNotNull(sName) && Utility.isNotNull(sPhoneNo) && Utility.isNotNull(sEmailId) ) { if (Utility.line2_validate(sName)) { if (Utility.validate(sPhoneNo)) { if (Utility.email_validate(sEmailId)) { //Get value from this Fragment FragmentY pf = new FragmentY (); Bundle args = new Bundle(); args.putString("mobile", sPhoneNo); args.putString("email",sEmailId); pf.setArguments(args); //Inflate the fragment getFragmentManager().beginTransaction().add(R.id.passwordLayout, pf).commit(); // Put Http parameter username with value of Name Edit View control params.put("name", sName); // Put Http parameter email with value of Email Edit Value control params.put("email", sEmailId); // Put Http parameter mobile with value of Mobile Edit Value control params.put("mobile", sPhoneNo); // Invoke Signup RESTful Web Service with Http parameters signUpWS(params); //Toast.makeText(getActivity().getApplicationContext(), "Success", Toast.LENGTH_SHORT).show(); //((MainActivity) getActivity()).navigatetoPasswordActivity(); } else { EmailId.setError("Enter valid Email"); } } else { Phone.setError("Enter valid Mobile"); } } else { Name.setError("Enter valid Name"); } } else { Toast.makeText(getActivity().getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_SHORT).show(); } } });
片段Y:
// Retrive the value from fragment x String strMobile = getArguments().getString("mobile"); String strEmail = getArguments().getString("email");
请任何人帮助我..
提前致谢!
您可以通过在片段中创建构造函数来将值传递给Farf
例如,
对于片段x在构造函数中传递值
PasswordFragment pf = new PasswordFragment (name, email, mobile);
对于fragmnet y,您可以从此构造函数中检索值
String name, email, mobile
public PasswordFragment(String name, String email, String mobile) {
// TODO Auto-generated constructor stub
this.name=name;
this.email=email;
this.mobile=mobile;
}
我知道Fragment应该通过它们所附加的Activity进行通信; 解决您的问题的一种方法是声明
final Activity activity = this.getActivity();
并使用它通过Activity属性(您可以选择私有或公共)来传递所需的值,例如
String value1;
String value2; //Into Activity
这样一来,您就可以从FragmentY中检索它们的值。
编辑:当然,在您的Fragment中声明最终的Activity对象时,您将需要强制转换为YourCustomActivity。
我建议您对此进行调查。 http://developer.android.com/training/basics/fragments/communicating.html
它非常干净和可取。任何片段都不应该直接进行通信。最好的方法是使用调用活动作为两个片段之间的中介
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.